; (function () {

    var schedule = new Schedule("Mobile", $('#hdnRelativeUrl').val());

    var page = {
        finishList: [],
        unFinishList: [],
        signList:[],
        ScheduleNotice: '',//注意事项
        saveType: 0, //预约保存类型，未预约：0；已预约：1 
        currentRecommend: null,
        showMobileScheduleCheckinInterface: false,//手机预约是否展示签到界面
        isScheduleTimeSelectPage: false,//当前显示选择预约时间界面
        saveExamScheduleFlag: false,//是否正在保存预约
        arrangeDayList: {}, //存储当前显示时间集合
        scheduleBreakFlag: false, //爽约标志
        scheduleExamRequestOld: {},
        addTimeConditionQuery: false,   //是否通过申请时间过滤查询
        scheduleExamRequest: {},
        //页面初始化
        init: function () {
            var h = $(window).height() - 90;
            $('#main_container .b-container').height(h);
            if (scheduleSelfShowSaveMultiButton) {
                var h = $(window).height() - 115;
                $('#main_container  .un-finish-container').css({ 'height': h });
            }

            schedule.days = 1;
            schedule.detailView = detailView;

            schedule.queryCondition.ScheduleRoute = scheduleRoute;
            if(detailView == '1' && (schedule.queryCondition.SubmitExamRequestInfo=='1' || schedule.queryCondition.PlacerOrderNO)){

                if(schedule.queryCondition.SubmitExamRequestInfo=='1'){
                    pageEvent.showDetailView(schedule.queryCondition,true);
                } else {
                    schedule.getExamRequestList(function(data) {
                        data[0].ScheduleRoute = scheduleRoute || 5;
                        pageEvent.showDetailView(data[0],true);
                    });
                }
            } else {
                detailView == ''; 
                $('#main_container').show();
                schedule.getExamRequestList(page.getExamRequestListCallback, function(errorMsg){
                    if (errorMsg) {
                        page.addTimeConditionQuery = true;
                    }
                    page.updateStatus();
                });
            }

            pageEvent.init();
        },

        //获取申请单列表
        getExamRequestListCallback: function (data, $flag) {
            pageEvent.judgingMobileScheduleCheckinInterface(data);//是否显示签到界面
            $('.b_name').text(data[0].Name);
            var list = [];
            var j = 0;
            for (var i = 0; i < data.length; i++) {
                if(data[i].NeedScheduleFlag){
                    list.splice(j,0,data[i]);
                    j++;
                } else {
                    list.push(data[i]);
                }
            }

            if (list.length > 0)
                var param = {
                    OutPatientNO: list[0].OutPatientNO,
                    InPatientNO: list[0].InPatientNO,
                    CardNO: list[0].CardNO,
                    IDCardNO: list[0].IDCardNO,
                    PatientMasterID: list[0].PatientMasterID,
                    MedRecNO: list[0].MedRecNO,
                    ScheduleRoute: scheduleRoute
                };
                schedule.CheckPatientLimit(param, function (ret) {
                    scheduleLimit = ret.scheduleLimit;
                    limitMsg = ret.limitMsg;
                    if (scheduleLimit == "1" )
                        pageEvent.scheduleLimit();
                });

            var finishTipsFlag = false, unFinishTipsFlag = false;

            //已预约
            var addFinish = function(exam){
                page.finishList.push(exam);
                page.bindFinish(exam);
            }
            //待预约
            var addUnFinish = function (exam) {
                page.unFinishList.push(exam);
                page.bindUnFinish(exam);
            }
            //已签到
            var addSign = function (exam) {
                page.signList.push(exam);
                page.bindSign(exam);
            }

            $.each(list, function (i, n) {
                list[i].ScheduleRoute = scheduleRoute || 5;
                if(list[i].orderList && list[i].orderList.length > 0){
                    $.each(list[i].orderList, function(j, m){
                        list[i].orderList[j].ScheduleRoute = scheduleRoute || 5;
                    });
                }
                if (list[i].ScheduleFlag && scheduleCompletedByResultStatus && scheduleCompletedByResultStatus.indexOf(list[i].ResultStatus) > -1) {
                    if (!finishTipsFlag && mobileScheduleTips) {
                        $('#main_container .finish-container').append("<div class='ifbook_items unbook_itemslist mobileScheduleTips'>" + mobileScheduleTips + "</div>");
                    }
                    finishTipsFlag = true;

                    if (pageEvent.judgingExamRequestMatchResultStatus(list[i])) { //该申请单自助预约已预约列表显示检查状态
                        //page.finishList.push(list[i]);
                        //page.bindFinish(list[i]);
                        addFinish(list[i]);
                    }
                } else if (!list[i].ScheduleFlag) { //待预约
                    if (!unFinishTipsFlag && mobileScheduleTips) {
                        $('#main_container .un-finish-container').append("<div class='ifbook_items unbook_itemslist mobileScheduleTips'>" + mobileScheduleTips + "</div>");
                    }
                    unFinishTipsFlag = true;

                    //待预约数据状态为已签到的在已签到显示
                    var signInStatus = schedule.GetSysParameterValueByExamRequest(list[i], signInCompletedByResultStatus);
                    if (signInStatus.indexOf(list[i].ResultStatus) == -1) {
                        //page.unFinishList.push(list[i]);
                        //page.bindUnFinish(list[i]);
                        addUnFinish(list[i]);
                    } else {
                        addSign(list[i]);
                    }

                } else {
                    if (pageEvent.judgingExamRequestMatchCheckin(list[i])) {    //已签到页签不显示
                        //page.signList.push(list[i]);
                        //page.bindSign(list[i]);
                        addSign(list[i]);
                    } else if (pageEvent.judgingExamRequestMatchResultStatus(list[i])) { //该申请单自助预约已预约列表显示检查状态
                        //page.finishList.push(list[i]);
                        //page.bindFinish(list[i]);
                        addFinish(list[i]);
                    }
                }
            });
            if ($flag == 'SignFinish') {
                if (page.finishList.length == 0) {
                    $('#main_container .b-container').height($(window).height() - 90);
                    $('#unbook_title').removeClass('ifactived');
                    $('#book_title').removeClass('ifactived');
                    $('#sign').addClass('ifactived');
                    $('.un-finish-container').hide();
                    $('#saveMulti').hide();
                    $('.finish-container').hide();
                    $('.finish-sign').show()
                }
            }
            page.updateStatus();

            $('.unbook_itemslist .not_schedule').on('click', function (e) {
                pageEvent.showNotScheduleMemo($(this),page.unFinishList);
                if (e && e.stopPropagation) {
                    e.stopPropagation();
                } else {
                    window.event.cancelBubble = true;
                }
                    
            });
  
            if ($('#book_title').hasClass('ifactived')) {
                $('#saveMulti').hide();
            } else if ($('#sign').hasClass('ifactived')) {
                $('#saveMulti').hide();
            } else if ($('#unbook_title').hasClass('ifactived')) {
                page.showMultiBtn();
            }

            if ($.trim(mobileScheduleShowTimeCondition) != "" && list.length == 0) {
                page.showTimeCondition();
            }
        },

        //检查申请
        bindUnFinish: function (exam, operateType) {
            $('body').css({ 'background': '#f2f2f2' });
            var self = exam.NeedScheduleFlag ? "1" : "0";
            var limtFlag = !(scheduleLimit == "2" || scheduleLimit == "3");
            var temp = '<div class="ifbook_items unbook_itemslist" data-who="unbook" data-PlacerOrderNO="' + exam.PlacerOrderNO + '" data-self="'+self+'">' +
                                 ' <div class="row ifbook_row ">' +
                             '<div class="col-md-11 row ifbook_rowdiv"  style="">' +
                                ' <div class="col-md-3" >' + exam.ServiceSectID + '</div>' +
                                ' <div class="col-md-9"  style="max-width: 75%;">' + exam.ProcedureName + '</div>' +
                            (exam.NeedScheduleFlag && limtFlag ? ' <div class="book" style="float:right;margin-right:3%"><span>预约</span></div>' : ' <div class="book" style="float:right;margin-right:3%;"><span style="background-color: #DDDDDD;">预约</span></div>') +
                             '</div>' +
                        ' </div>' +
                         '<div class="table_container" >' +
                             '<table class="b-table">' +
                                ' <tr>' +
                                     '<td class="align-right first_td apply_time" ><span>申请时间：</span></td>' +
                                    ' <td>' + imcis.convertDateFromJson(exam.RequestedDate) + '</td>' +
                                 '</tr>' +
                                     '<tr>' +
                                    ' <td class="align-right keshi">申请科室：</td>' +
                                    ' <td>' + exam.RequestDeptName + '</td>' +
                                ' </tr>' +
                            ' </table>' +
                            (exam.NeedScheduleFlag ? "" : '<div class=" book_pop not_schedule"><p>不提供自助预约</p></div>') +
                         '</div>' +
                     '</div>';
            if (operateType == "cancel") {
                if (mobileScheduleTips && $('#main_container .un-finish-container .mobileScheduleTips').length == 0)
                    $('#main_container .un-finish-container').append("<div class='ifbook_items unbook_itemslist mobileScheduleTips'>" + mobileScheduleTips + "</div>");
                if ($("#showTimeConditionTip").length > 0) {
                    $("#showTimeConditionTip").before(temp);
                } else {
                    $('#main_container .un-finish-container').append(temp);
                }
            } else {
                $('#main_container .un-finish-container').append(temp);
            }
            if (scheduleSelfShowSaveMultiButton) {
                var h = $(window).height() - 115;
                $('#main_container  .un-finish-container').css({ 'height': h });
            }
            
            page.showMultiBtn();
        },

        //根据检查类型、病人类型获取参数值，加减
        getDateByParameters: function (exam, date, sysParameters) {
            var startArrs = sysParameters.split("|");
            var dateStr = date;
            for (var key in startArrs) {
                var startArr = startArrs[key].split("=");
                var singleValFlag = startArr[0] != "" && !isNaN(startArr[0]);   //情况：参数设置为 30， parameter取数组的第一个值
                var ruleFlag = false;
                if (startArr[0] == exam.ServiceSectID) {
                    ruleFlag = true;
                } else if (startArr[0] == exam.PatientClass) {
                    ruleFlag = true;
                }
                else if (startArr[0] == (exam.ServiceSectID + "+" + exam.PatientClass)) {
                    ruleFlag = true;
                }
                if (ruleFlag || singleValFlag) {
                    var parameter = singleValFlag ? startArr[0] : startArr[1];
                    parameter = (!isNaN(parameter) && parameter.indexOf("-") == -1 ? "+" : "") + parameter;
                    var sign = parameter.indexOf("-") > -1 ? "-" : "";
                    parameter = parameter.replace("+", "$").replace("-", "$");
                    var parameterArr = parameter.split("$");
                    var fileName = parameterArr[0];
                    var fileValue = parseFloat(sign + parameterArr[1]);
                    dateStr = fileName == "" || exam[fileName] == null ? dateStr : imcis.convertDateFromJson(exam[fileName]);
                    dateStr = dateStr.replace(/-/g, ':').replace(' ', ':');
                    dateStr = dateStr.split(':');
                    var dateValue = new Date(dateStr[0], (dateStr[1] - 1), dateStr[2], dateStr[3], dateStr[4], '00');
                    //字段数据加减参数设置值 object instanceof Date
                    dateValue.setMinutes(dateValue.getMinutes() + fileValue);
                    //时间转指定格式字符串  imcis.date.dateStringFromDate(dateValue)
                    var dateStr = dateValue.Format("yyyy-MM-dd hh:mm");
                    dateStr = (typeof dateStr == "undefined" || dateStr == "null") ? "" : dateStr
                    return dateStr;
                } 
            }
            return dateStr;
        },

        getFinishBtnHtml: function (exam) {
            var limtFlag = !(scheduleLimit == "2" || scheduleLimit == "3");
            var editRightBySectID = editRightByServiceSectID == "" ? true : editRightByServiceSectID.indexOf(exam.ServiceSectID) > -1;
            var cancelRightBySectID = cancelRightByServiceSectID == "" ? true : cancelRightByServiceSectID.indexOf(exam.ServiceSectID) > -1;
            var editRightByPc = editRightByPatientClass == "" ? true : editRightByPatientClass.indexOf(exam.PatientClass) > -1;
            var cancelRightByPc = cancelRightByPatientClass == "" ? true : cancelRightByPatientClass.indexOf(exam.PatientClass) > -1;

            var allowSelfEditTimes = schedule.GetSysParameterValueByExamRequest(exam, scheduleAllowSelfEditTimes);
            var allowSelfEditFlag = true;
            var selfEditTimes = exam.SelfEditTimes == null ? 0 : exam.SelfEditTimes;
            if ($.trim(allowSelfEditTimes) != "") {
                allowSelfEditFlag = selfEditTimes < parseInt(allowSelfEditTimes);
            }

            var allowSelfCancelTimes = schedule.GetSysParameterValueByExamRequest(exam, scheduleAllowSelfCancelTimes);
            var allowSelfCancelFlag = true;
            var selfCancelTimes = exam.SelfCancelTimes == null ? 0 : exam.SelfCancelTimes;
            if ($.trim(allowSelfCancelTimes) != "") {
                allowSelfCancelFlag = selfCancelTimes < parseInt(allowSelfCancelTimes);
            }

            var allowEditTime = schedule.GetSysParameterValueByExamRequest(exam, ScheduleAutoNotAllowEditByScheduleDateAhead);
            var allowCancelTime = schedule.GetSysParameterValueByExamRequest(exam, ScheduleAutoNotAllowCancelByScheduleDateAhead);
            var scheduleStartDate = exam.ScheduleStartDate;

            var html = '';
            if (exam.NeedScheduleFlag) {
                html += '<ul><li class="checkExamRequest"><span>查看回执</span></li>';

                if (editRight == '1' && editRightBySectID && editRightByPc && limtFlag && allowSelfEditFlag) {
                    if (exam.allowUpdateSchedule) {
                        html += '<li class="edit_book" data-allowTimes="' + allowSelfEditTimes + '" data-editTimes="' + selfEditTimes + '"><span>修改预约</span></li>';
                    } else {
                        var status = exam.editResultStatus == false ? exam.ResultStatus : "";   //不允许修改
                        html += '<li class="unedit_book" data-notEditType="allowUpdateSchedule" data-allowUpdateTimes="' + allowEditTime + '" data-ScheduleStartDate="' + scheduleStartDate + '" data-resultStatus="' + status + '" data-patientClass="' + exam.PatientClass + '" data-serviceSectID="' + exam.ServiceSectID + '" data-scheduleRoute="' + exam.ScheduleRouteStr + '"><span>不提供修改</span></li>';
                    }
                } else {
                    html += '<li class="unedit_book" data-notEditType="' + (allowSelfEditFlag ? "" : "allowSelfEditTimes") + '" data-editTimes="' + selfEditTimes + '"><span>不提供修改</span></li>';
                }
                
                if (cancelRight == '1' && cancelRightBySectID && cancelRightByPc && limtFlag && allowSelfCancelFlag) {
                    if (exam.allowCancelSchedule) {
                        html += '<li class="cancle_book" data-allowTimes="' + allowSelfCancelTimes + '" data-cancelTimes="' + selfCancelTimes + '"><span>取消预约</span></li>'
                    } else if (exam.CancelResultStatusFlag == true) {
                        html += '<li class="uncancle_book" data-notCancelType="cancelResultStatus" data-resultStatus="' + exam.ResultStatus + '" data-patientClass="' + exam.PatientClass + '" data-serviceSectID="' + exam.ServiceSectID + '" data-scheduleRoute="' + exam.ScheduleRouteStr + '"><span>不提供取消</span></li>'
                    } else {
                        html += '<li class="uncancle_book" data-notCancelType="allowCancelSchedule" data-allowCancelTimes="' + allowCancelTime + '" data-ScheduleStartDate="' + scheduleStartDate + '"><span>不提供取消</span></li>'
                    }
                } else {
                    html += '<li class="uncancle_book" data-notCancelType="' + (allowSelfCancelFlag ? "" : "allowSelfCancelTimes") + '" data-cancelTimes="' + selfCancelTimes + '"><span>不提供取消</span></li>';
                }

                html += '</ul>';
            } else {
                html += '<ul><li class="checkExamRequest"><span>查看回执</span></li><li class="unedit_book not_schedule"><span>';
                html += exam.OperationMemo ? (exam.OperationMemo.length > 12 ? exam.OperationMemo.substr(0, 12) + '...' : exam.OperationMemo) : '不提供自助预约';
                html += '</span></li></ul>';
            }
            return html;
        },

        //已预约
        bindFinish: function (exam) {
            $('body').css({ 'background': '#f2f2f2' });
            var startDate = imcis.convertDateFromJson(exam.ScheduleStartDate);
            var endDate = imcis.convertDateFromJson(exam.ScheduleEndDate);
            var startTimeDetail = imcis.convertDateFromJson(exam.ScheduleStartTimeDetail);
            var endTimeDetail = imcis.convertDateFromJson(exam.ScheduleEndTimeDetail);
            var scheduleTime = startDate.substr(0, 16) + "-" + endDate.substr(11, 5);
            var showTimeType = schedule.GetSysParameterValueByExamRequest(exam, mobileScheduleShowTimeType);
            var scheduleTimeTitle = "预约时间";
            switch(showTimeType){
                case '1': 
                    if(exam.ScheduleStartTimeDetail) {
                        scheduleTime = startTimeDetail.substr(0, 16) + "-" + endTimeDetail.substr(11, 5);
                    }
                    break;
                case '2':
                    scheduleTime = startDate;
                    break;
                case '3':
                    if(exam.ScheduleStartTimeDetail) {
                        scheduleTime = startTimeDetail;
                    } else {
                        scheduleTime = startDate;
                    }
                    break;
                case '4':   //签到时间范围 开始时间  allowRegistByScheduleDateAhead  结束时间  allowRegistByScheduleDateLate
                    scheduleTimeTitle = "签到时间";
                    var startDate4 = page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead);
                    var endDate4 = page.getDateByParameters(exam, endDate, allowRegistByScheduleDateLate);
                    scheduleTime = startDate4.substr(0, 16) + "-" + endDate4.substr(11, 5);
                    break;
                case '5':   //签到开始时间
                    scheduleTimeTitle = "签到时间";
                    scheduleTime = page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead);
            }
            var ScheduleNotice = exam.ScheduleNotice;
            var ScheduleNoticehtml = '', qiandaoStr = '';
            var mobileCheckinFlag = false;//该检查项目是否支持手机签到
            var scheduleRouteStr = imcis.schedule.getScheduleRouteStr(scheduleRoute);
            exam.allowUpdateSchedule = schedule.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead(exam, ScheduleAutoNotAllowEditByScheduleDateAhead);//判断是否允许修改预约
            if(exam.ResultStatus && exam.allowUpdateSchedule && editResultStatus) {
                var resultStatus = imcis.schedule.getSysParamValueByScheduleRoute(editResultStatus, scheduleRouteStr, exam.ServiceSectID, exam.PatientClass);
                if(resultStatus && resultStatus.indexOf(exam.ResultStatus) == -1) {
                    exam.allowUpdateSchedule = false;
                    exam.editResultStatus = false;
                    exam.ScheduleRouteStr = scheduleRouteStr;
                }
            }
            exam.allowCancelSchedule = schedule.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead(exam, ScheduleAutoNotAllowCancelByScheduleDateAhead)//判断是否允许取消预约
            if(exam.ResultStatus && exam.allowCancelSchedule && cancelResultStatus) {
                var resultStatus = imcis.schedule.getSysParamValueByScheduleRoute(cancelResultStatus, scheduleRouteStr, exam.ServiceSectID, exam.PatientClass);
                if ($.trim(resultStatus) == "" || (resultStatus && resultStatus.indexOf(exam.ResultStatus) == -1)) {
                    exam.allowCancelSchedule = false;
                    exam.CancelResultStatusFlag = true;
                    exam.ScheduleRouteStr = scheduleRouteStr;
                }
            }
            
            if (page.showMobileScheduleCheckinInterface) {
                var mobileScheduleScanCodeCheckinResult = schedule.GetSysParameterValueByExamRequest(exam, mobileScheduleScanCodeCheckin);
                var mobileScheduleCheckinCodeResult = schedule.GetSysParameterValueByExamRequest(exam, mobileScheduleCheckinCode);
                //根据mobileScheduleDirectCheckin参数，是否隐藏直接签到菜单
                var mobileScheduleDirectCheckinResult = schedule.GetSysParameterValueByExamRequest(exam, mobileScheduleDirectCheckin);
                var checkinFlag = mobileScheduleScanCodeCheckinResult == "0" && mobileScheduleCheckinCodeResult == "0" && mobileScheduleDirectCheckinResult == "0";
                var showBtn1 = (mobileScheduleScanCodeCheckinResult == "1" && mobileScheduleCheckinCodeResult == "0" && mobileScheduleDirectCheckinResult == "0")
                    || (mobileScheduleScanCodeCheckinResult == "0" && mobileScheduleCheckinCodeResult == "1" && mobileScheduleDirectCheckinResult == "0")
                    || (mobileScheduleScanCodeCheckinResult == "0" && mobileScheduleCheckinCodeResult == "0" && mobileScheduleDirectCheckinResult == "1");
                if (exam.NeedScheduleFlag && pageEvent.judgingExamRequestMatchCheckin(exam) && !checkinFlag) {
                    qiandaoStr = '<div class=" col-md-3 attation sign">签到'; 
                    qiandaoStr += showBtn1 ? '' : '<span class="triangle">';
                    qiandaoStr += '</span></div>'; 
                }
            } else {
                //不展示签到界面，则已预约申请单项目不需要显示签到
            }
            
            if (ScheduleNotice) {
                var ScheduleNoticeStr = '';
                var tdStr = '';
                if ((ScheduleNotice.length > 7)) {
                    ScheduleNoticeStr = ScheduleNotice.substring(0, 7) + '...';
                    tdStr = '<td class="scheduleNotice attention_td" >' + ScheduleNoticeStr + '</td>';
                } else {
                    tdStr = '<td class="scheduleNotice">' + ScheduleNotice + '</td>';
                }
                ScheduleNoticehtml =   '<tr>' +
                '<td class="align-right add_att">注意事项：</td>' + tdStr +
                 ' </tr>'
            }

            var signStartDate = page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead);
            var signEndDate = page.getDateByParameters(exam, endDate, allowRegistByScheduleDateLate);
            var self = exam.NeedScheduleFlag ? "1" : "0";

            var temp = '<div class="ifbook_items"  data-who="booked"  data-PlacerOrderNO="' + exam.PlacerOrderNO + '" data-ObservationUID="' + exam.ObservationUID + '" data-self="' + self + '" data-scheduletime="' + scheduleTime + '" data-servicesectid="' + exam.ServiceSectID + '" data-patientclass="' + exam.PatientClass + '" data-signstartdate="' + signStartDate + '" data-signenddate="' + signEndDate + '" data-signscheduletime="' + (page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead).substr(0, 16) + "-" + page.getDateByParameters(exam, endDate, allowRegistByScheduleDateLate).substr(11, 5))  + '">' +
                        '<div class="row ifbook_row">' +
                            '<div class="col-md-9  ifbook_rowdiv row" style="width: 100%">' +
                               ' <div class=" col-md-3">' + exam.ServiceSectID + '</div>' +
                                '<div class=" col-md-9" style="max-width:80%;">' + exam.ProcedureName + '</div>' + qiandaoStr +
                           ' </div>' +
                        '</div>' +
                       ' <div class="table_container">' +
                            '<table class="b-table">' +
                               ' <tr>' +
                                    '<td class="align-right first_td apply_time" >' + scheduleTimeTitle + '：</td>' +
                                    '<td class="scheduletime">' + scheduleTime + '</td>' +
                                '</tr>' +
                                '<tr>' +
                                    '<td class="align-right add_ph">检查地点：</td>' +
                                    '<td class="observationlocation" style="font-weight:bold;color:red;">' + (exam.ResourceLocation || '') + '</td>' +
                               ' </tr>' + ScheduleNoticehtml+
                            '</table>' +
                            '<div class=" book_pop">' +
                                page.getFinishBtnHtml(exam) +
                            '</div>' +
                        '</div>' +
                    '</div>';
            if (mobileScheduleTips && $('#main_container .finish-container .mobileScheduleTips').length == 0)
                $('#main_container .finish-container').append("<div class='ifbook_items unbook_itemslist mobileScheduleTips'>" + mobileScheduleTips + "</div>");
            $('#main_container .finish-container').append(temp);
            $('#main_container .finish-container').height($(window).height() - 100);
        },

        //检查申请
        bindUnFinishForDetailView: function (exam) {
            $('body').css({ 'background': '#f2f2f2' });
            var self = exam.NeedScheduleFlag ? "1" : "0";
            var temp = '<div class="ifbook_items unbook_itemslist" data-PlacerOrderNO="' + exam.PlacerOrderNO + '" data-self="' + self + '">' +
                                 ' <div class="row ifbook_row ">' +
                             '<div class="col-md-11 row ifbook_rowdiv"  style="">' +
                                ' <div class="col-md-3" >' + exam.ServiceSectID + '</div>' +
                                ' <div class="col-md-9"  style="max-width: 75%;">' + exam.ProcedureName + '</div>' +
                             '</div>' +
                        ' </div>' +
                         '<div class="table_container" >' +
                             '<table class="b-table">' +
                                ' <tr>' +
                                     '<td class="align-right first_td apply_time" ><span>申请时间：</span></td>' +
                                    ' <td>' + imcis.convertDateFromJson(exam.RequestedDate) + '</td>' +
                                 '</tr>' +
                                     '<tr>' +
                                    ' <td class="align-right keshi">申请科室：</td>' +
                                    ' <td>' + exam.RequestDeptName + '</td>' +
                                ' </tr>' +
                            ' </table>' +
                            (exam.NeedScheduleFlag ? "" : '<div class=" book_pop not_schedule"><p>不提供自助预约</p></div>') +
                         '</div>' +
                     '</div>';
            $('#examRequestResult_container,#examRequestResult_main').show();
            $('#examRequestResult_title').text('预约结果');
            $('#examRequestResult_main').append(temp);
            $('#examRequestResult_main').css({ 'width': '100%', 'margin-top': '48px' });
            if (detailView == '1' && !returnUrl) {
                $('#examRequestResult_back').off();
                $('#examRequestResult_back').parent().css({ 'display': 'none' });
            }
        },

        //已预约
        bindFinishForDetailView: function (exam) {
            $('body').css({ 'background': '#f2f2f2' });
            var startDate = imcis.convertDateFromJson(exam.ScheduleStartDate);
            var endDate = imcis.convertDateFromJson(exam.ScheduleEndDate);
            var startTimeDetail = imcis.convertDateFromJson(exam.ScheduleStartTimeDetail);
            var endTimeDetail = imcis.convertDateFromJson(exam.ScheduleEndTimeDetail);
            var scheduleTime = startDate.substr(0, 16) + "-" + endDate.substr(11, 5);
            var showTimeType = schedule.GetSysParameterValueByExamRequest(exam, mobileScheduleShowTimeType);
            var scheduleTimeTitle = "预约时间";
            switch (showTimeType) {
                case '1':
                    if (exam.ScheduleStartTimeDetail) {
                        scheduleTime = startTimeDetail.substr(0, 16) + "-" + endTimeDetail.substr(11, 5);
                    }
                    break;
                case '2':
                    scheduleTime = startDate;
                    break;
                case '3':
                    if (exam.ScheduleStartTimeDetail) {
                        scheduleTime = startTimeDetail;
                    } else {
                        scheduleTime = startDate;
                    }
                    break;
                case '4':   //签到时间范围 开始时间  allowRegistByScheduleDateAhead  结束时间  allowRegistByScheduleDateLate
                    scheduleTimeTitle = "签到时间";
                    var startDate4 = page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead);
                    var endDate4 = page.getDateByParameters(exam, endDate, allowRegistByScheduleDateLate);
                    scheduleTime = startDate4.substr(0, 16) + "-" + endDate4.substr(11, 5);
                    break;
                case '5':   //签到开始时间
                    scheduleTimeTitle = "签到时间";
                    scheduleTime = page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead);
            }
            var ScheduleNotice = exam.ScheduleNotice;
            var ScheduleID = exam.ScheduleID;
            var ResourceLocation = exam.ResourceLocation;
            if (ScheduleID == '' || ScheduleID == null || ScheduleID == 'undefined') { ScheduleID = ''; }
            if (ResourceLocation == '' || ResourceLocation == null || ResourceLocation == 'undefined') { ResourceLocation = ''; }
            var ResourceRoom = '';
            if (exam.ScheduleResource && exam.ScheduleResource.ResourceRoom) { ResourceRoom = exam.ScheduleResource.ResourceRoom; }
            var ScheduleNoticehtml = '', qiandaoStr = '';
            var mobileCheckinFlag = false;//该检查项目是否支持手机签到
            var scheduleRouteStr = imcis.schedule.getScheduleRouteStr(scheduleRoute);
            exam.allowUpdateSchedule = schedule.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead(exam, ScheduleAutoNotAllowEditByScheduleDateAhead);//判断是否允许修改预约
            if(exam.ResultStatus && exam.allowUpdateSchedule && editResultStatus) {
                var resultStatus = imcis.schedule.getSysParamValueByScheduleRoute(editResultStatus, scheduleRouteStr, exam.ServiceSectID, exam.PatientClass);
                if(resultStatus && resultStatus.indexOf(exam.ResultStatus) == -1) {
                    exam.allowUpdateSchedule = false;
                    exam.editResultStatus = false;
                    exam.ScheduleRouteStr = scheduleRouteStr;
                }
            }
            exam.allowCancelSchedule = schedule.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead(exam, ScheduleAutoNotAllowCancelByScheduleDateAhead)//判断是否允许取消预约
            if (exam.ResultStatus && exam.allowCancelSchedule && cancelResultStatus) {
                var resultStatus = imcis.schedule.getSysParamValueByScheduleRoute(cancelResultStatus, scheduleRouteStr, exam.ServiceSectID, exam.PatientClass);
                if ($.trim(resultStatus) == "" || (resultStatus && resultStatus.indexOf(exam.ResultStatus) == -1)) {
                    exam.allowCancelSchedule = false;
                    exam.cancelResultStatusFlag = true;
                    exam.scheduleRouteStr = scheduleRouteStr;
                }
            }
            if (page.showMobileScheduleCheckinInterface) {
                if (exam.NeedScheduleFlag && pageEvent.judgingExamRequestMatchCheckin(exam)) {
                    qiandaoStr = '<div class=" col-md-3 attation sign">签到<span class="triangle"></span></div>';
                }
            } else {
                //不展示签到界面，则已预约申请单项目不需要显示签到
            }

            if (ScheduleNotice) {
                var ScheduleNoticeStr = '';
                var tdStr = '';
                if ((ScheduleNotice.length > 7)) {
                    ScheduleNoticeStr = ScheduleNotice.substring(0, 7) + '...';
                    tdStr = '<td class="scheduleNotice attention_td" >' + ScheduleNoticeStr + '</td>';
                } else {
                    tdStr = '<td class="scheduleNotice">' + ScheduleNotice + '</td>';
                }
                ScheduleNoticehtml = '<tr>' +
                '<td class="align-right add_att">注意事项：</td>' + tdStr +
                 ' </tr>'
            }

            var signStartDate = page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead);
            var signEndDate = page.getDateByParameters(exam, endDate, allowRegistByScheduleDateLate);
            var self = exam.NeedScheduleFlag ? "1" : "0";
            var limtFlag = !(scheduleLimit == "2" || scheduleLimit == "3");
            var editRightBySectID = editRightByServiceSectID == "" ? true : editRightByServiceSectID.indexOf(exam.ServiceSectID) > -1;
            var cancelRightBySectID = cancelRightByServiceSectID == "" ? true : cancelRightByServiceSectID.indexOf(exam.ServiceSectID) > -1;
            var editRightByPc = editRightByPatientClass == "" ? true : editRightByPatientClass.indexOf(exam.PatientClass) > -1;
            var cancelRightByPc = cancelRightByPatientClass == "" ? true : cancelRightByPatientClass.indexOf(exam.PatientClass) > -1;
            var allowSelfEditTimes = schedule.GetSysParameterValueByExamRequest(exam, scheduleAllowSelfEditTimes);
            var allowSelfEditFlag = true;
            var selfEditTimes = exam.SelfEditTimes == null ? 0 : exam.SelfEditTimes;
            if ($.trim(allowSelfEditTimes) != "") {
                allowSelfEditFlag = selfEditTimes < parseInt(allowSelfEditTimes);
            }

            var allowSelfCancelTimes = schedule.GetSysParameterValueByExamRequest(exam, scheduleAllowSelfCancelTimes);
            var allowSelfCancelFlag = true;
            var selfCancelTimes = exam.SelfCancelTimes == null ? 0 : exam.SelfCancelTimes;
            if ($.trim(allowSelfCancelTimes) != "") {
                allowSelfCancelFlag = selfCancelTimes < parseInt(allowSelfCancelTimes);
            }
            var temp = '<div class="ifbook_items"  data-who="booked"   data-PlacerOrderNO="' + exam.PlacerOrderNO + '" data-ObservationUID="' + exam.ObservationUID + '" data-self="' + self + '" data-scheduletime="' + scheduleTime + '" data-servicesectid="' + exam.ServiceSectID + '" data-patientclass="' + exam.PatientClass + '" data-signstartdate="' + signStartDate + '" data-signenddate="' + signEndDate + '" data-signscheduletime="' + (page.getDateByParameters(exam, startDate, allowRegistByScheduleDateAhead).substr(0, 16) + "-" + page.getDateByParameters(exam, endDate, allowRegistByScheduleDateLate).substr(11, 5))  + '">' +
                        '<div class="row ifbook_row">' +
                            '<div class="col-md-9  ifbook_rowdiv row" style="width: 100%">' +
                               ' <div class=" col-md-3">' + exam.ServiceSectID + '</div>' +
                                '<div class=" col-md-9" style="max-width:80%;">' + exam.ProcedureName + '</div>' + qiandaoStr +
                           ' </div>' +
                        '</div>' +
                       ' <div class="table_container">' +
                            '<table class="b-table">' +
                               ' <tr>' +
                                    '<td class="align-right first_td apply_time" >预约时间：</td>' +
                                    '<td class="scheduletime">' + scheduleTime + '</td>' +
                                '</tr>' +
                                 ' <tr>' +
                                    '<td class="align-right first_td queue" >排&nbsp;&nbsp;队&nbsp;&nbsp;号：</td>' +
                                    '<td class="scheduletime">' + ScheduleID + '</td>' +
                                '</tr>' +
                                  ' <tr>' +
                                    '<td class="align-right first_td resource_room" >检查机房：</td>' +
                                    '<td class="scheduletime">' + ResourceRoom + '</td>' +
                                '</tr>' +
                                '<tr>' +
                                    '<td class="align-right add_ph">检查地点：</td>' +
                                    '<td class="observationlocation" style="font-weight:bold;color:red;">' + ResourceLocation + '</td>' +
                               ' </tr>' + ScheduleNoticehtml +
                            '</table>' +
                            '<div class=" book_pop">' +
                            (exam.NeedScheduleFlag ?
                               '<ul><li class="checkExamRequest"><span>查看回执</span></li>' +
                                    (editRight == '1' && editRightBySectID && editRightByPc && limtFlag && allowSelfEditFlag ?
                                        (exam.allowUpdateSchedule ?
                                            '<li class="edit_book" data-allowTimes="' + allowSelfEditTimes + '" data-editTimes="' + selfEditTimes + '"><span>修改预约</span></li>' :
                                            '<li class="unedit_book"><span>不提供修改</span></li>') :
                                        '<li class="unedit_book" data-notEditType="' + (allowSelfEditFlag ? "" : "allowSelfEditTimes") + '" data-editTimes="' + selfEditTimes + '"><span>不提供修改</span></li>') +
                                    (cancelRight == '1' && cancelRightBySectID && cancelRightByPc && limtFlag && allowSelfCancelFlag ?
                                        (exam.allowCancelSchedule ?
                                            '<li class="cancle_book" data-allowTimes="' + allowSelfCancelTimes + '" data-cancelTimes="' + selfCancelTimes + '"><span>取消预约</span></li>' :
                                            '<li class="uncancle_book"><span>不提供取消</span></li>') :
                                        '<li class="uncancle_book" data-notCancelType="' + (allowSelfCancelFlag ? "" : "allowSelfCancelTimes")+'" data-cancelTimes="' + selfCancelTimes + '"><span>不提供取消</span></li>') +
                                '</ul>' :
                                '<ul><li class="checkExamRequest"><span>查看回执</span></li><li class="unedit_book not_schedule"><span>' +
                                (exam.OperationMemo ? exam.OperationMemo.length > 12 ? exam.OperationMemo.substr(0, 12) + '...' : exam.OperationMemo : '不提供自助预约')
                                + '</span></li></ul>') +
                            '</div>' +
                        '</div>' +
                    '</div>';
            $('#examRequestResult_container,#examRequestResult_main').show();
            $('#examRequestResult_title').text('预约结果');
            $('#examRequestResult_main').append(temp);
            $('#examRequestResult_main').css({ 'width': '100%', 'margin-top': '48px' });
            if (detailView == '1' && !returnUrl) {
                $('#examRequestResult_back').off();
                $('#examRequestResult_back').parent().css({ 'display': 'none' });
            }
        },

        //已签到
        bindSign: function (exam) {
            $('body').css({ 'background': '#f2f2f2' });
            var scheduleTimeTitle = "签到时间";
            var signInDate = imcis.convertDateFromJson(exam.SignInDate); 
            var regTime = imcis.convertDateFromJson(exam.RegTime);
            var scheduleTime = signInDate == "" ? regTime : signInDate;
            var ScheduleID = exam.ScheduleID;
            var ResourceLocation = exam.ResourceLocation;
            if (ScheduleID == '' || ScheduleID == null || ScheduleID == 'undefined') { ScheduleID = ''; }
            if (ResourceLocation == '' || ResourceLocation == null || ResourceLocation == 'undefined') { ResourceLocation = ''; }
            var ResourceRoom = '';
            if (exam.ScheduleResource && exam.ScheduleResource.ResourceRoom) { ResourceRoom = exam.ScheduleResource.ResourceRoom; }
            
            var examTypeCheckShowField = imcis.schedule.getSysParamValue(checkShowField,exam.ServiceSectID) || '预约时间,排队号,检查机房,检查地点,注意事项'; 
            var qiandaoStr = '<div class=" col-md-3 pull-right sign-code" data-url="' + examReportCodeUrl + '" data-observationUID="' + exam.ObservationUID + '" >结果码</div>';
            var self = exam.NeedScheduleFlag ? "1" : "0";

            var temp = '<div class="ifbook_items"  data-PlacerOrderNO="' + exam.PlacerOrderNO + '" data-self="' + self + '">' +
                        '<div class="row ifbook_row">' +
                            '<div class="col-md-9  ifbook_rowdiv row" style="width: 100%">' +
                               ' <div class=" col-md-3">' + exam.ServiceSectID + '</div>' +
                                '<div class=" col-md-9" style="max-width:80%;">' + exam.ProcedureName + '</div>' +qiandaoStr+
                           ' </div>' +
                        '</div>' +
                       ' <div class="table_container">' +
                            '<table class="b-table">';
            if(examTypeCheckShowField.indexOf('预约时间') > -1) {
                temp += '<tr>' +
                            '<td class="align-right first_td apply_time" >'+scheduleTimeTitle+'：</td>' + 
                            '<td class="scheduletime">' + scheduleTime + '</td>' +
                        '</tr>';
            }
            if(examTypeCheckShowField.indexOf('排队号') > -1) {
                temp += '<tr>' +
                            '<td class="align-right first_td queue" >排&nbsp;&nbsp;队&nbsp;&nbsp;号：</td>' +
                            '<td class="scheduletime">' + ScheduleID + '</td>' +
                        '</tr>';
            }
            if(examTypeCheckShowField.indexOf('检查机房') > -1) {
                temp += '<tr>' +
                            '<td class="align-right first_td resource_room" >检查机房：</td>' +
                            '<td class="scheduletime">' + ResourceRoom + '</td>' +
                        '</tr>';
            }
            if(examTypeCheckShowField.indexOf('检查地点') > -1) {
                temp += '<tr>' +
                            '<td class="align-right add_ph">检查地点：</td>' +
                            '<td class="observationlocation" style="font-weight:bold;color:red;">' + ResourceLocation + '</td>' +
                        '</tr>';
            }

            if(examTypeCheckShowField.indexOf('注意事项') > -1 && exam.ScheduleNotice) {
                var ScheduleNoticeStr = '';
                var tdStr = '';
                if ((exam.ScheduleNotice.length > 7)) {
                    ScheduleNoticeStr = exam.ScheduleNotice.substring(0, 7) + '...';
                    tdStr = '<td class="observationlocation attention_td" >' + ScheduleNoticeStr + '</td>';
                } else {
                    tdStr = '<td class="observationlocation">' + exam.ScheduleNotice + '</td>';
                }
                temp += '<tr>' +
                            '<td class="align-right add_att">注意事项：</td>' + tdStr +
                        '</tr>';
            }
                     
            if (examTypeCheckShowField.indexOf('检查状态') > -1) {
                temp += '<tr>' +
                    '<td class="align-right state_ph">检查状态：</td>' +
                    '<td style="color:#2A9D90;">' + exam.ResultStatus + '</td>' +
                    '</tr>';
            }

            temp += '</table></div></div>';
            $('#main_container .finish-sign').append(temp);
            $('#main_container .finish-sign').height($(window).height() - 100);
            if ("书写完成,审核完成,修订完成".indexOf(exam.ResultStatus) > -1) {
                $('#main_container .finish-sign .ifbook_items[data-PlacerOrderNO="' + exam.PlacerOrderNO + '"] .scheduletime').css("color","#ccc");
                $('#main_container .finish-sign .ifbook_items[data-PlacerOrderNO="' + exam.PlacerOrderNO + '"] .observationlocation').css("color", "#ccc");
            }
        },

        //更新申请单状态
        updateStatus: function (sgFlag) {
            $('#book_title .booknum').text('  (' + page.finishList.length + ')');
            $('#unbook_title .unbooknum').text('  (' + page.unFinishList.length + ')');
            $('#sign .booknum').text('  (' + page.signList.length + ')');
            if (page.unFinishList.length == 0) {
                $(".un-finish-container").html('<div id="noUnFinishData">没有待预约记录' + (scheduleNoExamRequestTips || "") + '</div>');
                if (page.addTimeConditionQuery) {
                    $("#noUnFinishData").css({ "height": "auto","margin-bottom": "0"});
                    page.showTimeCondition();
                }
                $('#saveMulti').hide();
            } else {
                if($('.un-finish-container').css('display') != 'none'){
                    page.showMultiBtn();
                }
                $('#noUnFinishData').remove();
            }
            if (page.finishList.length == 0) {
                $(".finish-container").html('<div id="noFinishData" class="noFinishData">没有已预约记录</div>');
            } else {
                $("#noFinishData").remove();
            }
            if (page.signList.length == 0) {
                $(".finish-sign").html('<div id="noSignFinishData" class="noFinishData">没有已签到记录</div>');
            } else {
                $("#noSignFinishData").remove();
            }
            if (!sgFlag && page.unFinishList.length == 0 && page.finishList.length && $('.ifactived').find('.title').text() == '待预约') {//当未预约为0 时显示已预约
                $('#main_container .b-container').height($(window).height() - 90);
                $('#unbook_title').removeClass('ifactived');
                $('.un-finish-container').hide();
                $('#book_title').addClass('ifactived');
                $('.finish-container').show();
                $('#sign').removeClass('ifactived');
                $('.finish-sign').hide();
                $('#saveMulti').hide();
            } else if (!sgFlag && page.unFinishList.length == 0 && page.finishList.length == 0 && page.signList.length) {//当未预约为0 已预约都为0时显示签到
                $('#main_container .b-container').height($(window).height() - 90);
                $('#unbook_title').removeClass('ifactived');
                $('#book_title').removeClass('ifactived');
                $('#sign').addClass('ifactived');
                $('.un-finish-container').hide();
                $('#saveMulti').hide();
                $('.finish-container').hide();
                $('.finish-sign').show();
            }
        },
        //显示一键预约
        showMultiBtn: function () {
            var canAuto = false;
            for (var i = 0; i < page.unFinishList.length; i++) {
                if (page.unFinishList[i].NeedScheduleFlag) {
                    canAuto = true;
                    break;
                }
            }

            if (canAuto && scheduleSelfShowSaveMultiButton) {
                $('#saveMulti').show();
            } else {
                $('#saveMulti').hide();
            }
        },
        //手机端待预约列显示时间查询条件
        showTimeCondition: function () {
            if ($("#main_container .un-finish-container #showTimeConditionTip").length > 0) {
                $("#main_container .un-finish-container #showTimeConditionTip").remove();
            }
            $('#main_container .un-finish-container').append(`<div id="showTimeConditionTip"><a id="showTimeCondition">${mobileScheduleShowTimeCondition}</a></div>`);
            if ($('#saveMulti').css('display') != "none") {
                $('#main_container .un-finish-container #showTimeConditionTip').css("height", "100px");
            }

            $('#main_container .un-finish-container').on('click', '#showTimeCondition', function () {
                page.addTimeConditionQuery = true;
                var dateTime = pageEvent.isAndroid() ? "androidDateTime" : "appleDateTime";
                var queryDateShortcutList = [];
                if (queryDateShortcut && queryDateShortcut != "[]") {
                    queryDateShortcutList = eval(queryDateShortcut);
                }
                var selHtml = '<select id="queryDateShortcut" style="width:130px;height:34px;">';
                $.each(queryDateShortcutList, function (index, item) {
                    if (item.id != "All")
                        selHtml += `<option value="${item.id}">${item.text}</option>`;
                });
                selHtml += '</select>';
                var html = `
                    <div style="display: grid;grid-template-columns: 150px auto;grid-template-rows: 55px 55px;text-align:right;">
                        <div style="padding-right:5px;line-height: 38px;font-size: 15px;">${selHtml}</div>
                        <div><input id="txt-datetimestart" class="datebox ${dateTime}" type="date" placeholder="选择开始时间" value="" style="display: block;" /></div>
                        <div style="padding-right:5px;line-height: 38px;font-size: 15px;">到</div>
                        <div><input id="txt-datetimeend" class="datebox ${dateTime}" type="date" placeholder="选择结束时间" value="" style="display: block;" /></div>
                    </div>
                    `;
                schedule.comfirmSearch(html, function () {
                    var requestedDateBegin = $('#txt-datetimestart').val();
                    var requestedDateEnd = $('#txt-datetimeend').val();
                    if ($.trim(requestedDateBegin) == "") {
                        schedule.alert("申请开始时间不能为空！");
                        return;
                    }
                    if ($.trim(requestedDateEnd) == "") {
                        schedule.alert("申请结束时间不能为空！");
                        return;
                    }
                    schedule.queryCondition.RequestedDateBegin = requestedDateBegin + " 00:00:00";
                    schedule.queryCondition.RequestedDateEnd = requestedDateEnd + " 23:59:59";
                    schedule.getExamRequestList(function (data) {
                        page.finishList = [];
                        page.unFinishList = [];
                        page.signList = [];
                        page.updateStatus();
                        page.getExamRequestListCallback(data);
                    });
                });

                $("#queryDateShortcut").bind('change', function () {
                    pageEvent.getQueryDateMenuItemClick(this.value);
                });
                pageEvent.getQueryDateMenuItemClick(queryDateShortcutList[0].id);
            });
        }
    };

    var pageEvent = {
        //事件初始化
        init: function () {
            //点击显示检查申请
            $('.ifbook').on('click', '#unbook_title', pageEvent.showUnFinish);
            //点击显示已预约
            $('.ifbook').on('click', '#book_title', pageEvent.showFinish);
            //点击显示已签到
            $('.ifbook').on('click', '#sign', pageEvent.showSign);
            //取消预约
            $('.b-container,#examRequestResult_container').on('click', '.cancle_book', pageEvent.cancelSchedule);
            //修改预约时间
            $('.b-container,#examRequestResult_container').on('click', '.edit_book', pageEvent.editSchedule);
            //不提供修改
            $('.b-container,#examRequestResult_container').on('click', '.unedit_book', pageEvent.scheduleLimit);
            //不提供取消
            $('.b-container,#examRequestResult_container').on('click', '.uncancle_book', pageEvent.scheduleLimit); 
            //检查申请开始预约
            if (editRight == '1') {
                $('.b-container').on('click', '.unbook_itemslist', pageEvent.startSchedule);
            } else {
                $('.b-container').on('click', '.unbook_itemslist', function () {
                    schedule.alert("没有预约权限！");
                });
            }

            //选中时间
            $('#time_container').on('click', '.ampm_comtainer_sub .width_continer div', pageEvent.selectTime);

            //一键预约多个检查申请
            $('#saveMulti').on('click', pageEvent.saveMultiExamSchedule);
            //保存预约
            $('#save_time').on('click', pageEvent.saveExamSchedule);

            //时间页面返回
            $('#backToMain').on('click', function () {
                if (detailView == '1') {
                    if ($('#time_container').attr('data-whoOpen') == 'examRequestResult_container') {
                        $('#time_container').hide();
                        $('#examRequestResult_container').show();
                    }else if(returnUrl) {
                        pageEvent.returnToUrl();
                    }
                } else {
                    $('#main_container').show();
                    $('#time_container').hide();
                    $('.ampm_comtainer_sub').html('');
                    $('body').css({ 'background': '#f2f2f2' });
                    page.isScheduleTimeSelectPage = false;
                }
            });

            //已预约点击后出现预约事项
            $('#main_container,#examRequestResult_container').on('click', '.attention_td', function () {
                var $this = $(this);
                var placerOrderNO = $this.closest('.ifbook_items').data("placerorderno");
                $('#attantion_title').text('注意事项');
                $('#sign_main').hide();
                $('#attion_main').height($(window).height() - 77);
                var arr = page.finishList;
                if ($this.parents('#examRequestResult_container').length > 0) {
                    $('#attantion_container').attr('data-whoOpen', 'examRequestResult_container');
                } else {
                    $('#attantion_container').attr('data-whoOpen', 'main_container');
                    if ($('.ifactived').find('.title').text() == '已签到') { arr = page.signList; }
                }

                $.each(arr, function (i, n) {
                    if (placerOrderNO == n.PlacerOrderNO) {
                        $('#attion_main').text(n.ScheduleNotice);
                        $('#attantion_container').show();
                        $('body').css({ 'background': '#fff' });
                        if ($this.parents('#examRequestResult_container').length > 0) {
                            $('#examRequestResult_container').hide();
                        } else {
                            $('#main_container').hide();
                        }
                        return false;
                    }
                });
            });

            //已预约或预约结果点击查看回执
            $('#main_container,#examRequestResult_container').on('click', '.checkExamRequest', function () {
                var $this = $(this);
                $('#examRequest_container').attr({ 'data-whoOpen': '' }); 
                $('#time_container').attr({ 'data-whoOpen': '' });
                var order = {};
                var arr = page.finishList;
                var placerOrderNO = $this.closest('.ifbook_items').data("placerorderno");
                $.each(arr, function (i, n) {
                    if (placerOrderNO == n.PlacerOrderNO) {
                        order = n;
                    }
                });
                pageEvent.alertExamRequest(order,$this);
            });

            //一键预约alert关闭
            $('#attation_back').click(function () {
                if ($('#attantion_title').text() == '签到码') {
                    if ($('#attantion_container').attr('data-whoOpen') == 'examRequestResult_container') {
                        $('#attantion_container').hide();
                        $('#examRequestResult_container').show();
                    } else if ($(".ifactived").attr('id') == 'book_title') {
                        $('#attantion_container').hide();
                        $('#main_container').show();
                        $('body').css({ 'background': '#f2f2f2' });
                        $('.finish-container,.un-finish-container,.finish-sign').html('');
                        page.finishList = [];
                        page.unFinishList = [];
                        page.signList = [];
                        schedule.getExamRequestList(page.getExamRequestListCallback);
                        $('#main_container .b-container').height($(window).height() - 90);
                        $('#unbook_title').removeClass('ifactived');
                        $('#book_title').removeClass('ifactived');
                        $('#sign').addClass('ifactived');
                        $('.un-finish-container').hide();
                        $('#saveMulti').hide();
                        $('.finish-container').hide();
                        $('.finish-sign').show();
                    }
                   
                } else if ($('#attantion_title').text() == '注意事项' && $('#attantion_container').attr('data-whoOpen') == 'examRequestResult_container') {
                    $('#attantion_container').hide();
                    $('#examRequestResult_container').show();
                } else {
                    $('#attantion_container').hide();
                    $('#main_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                }
            });

            //关闭申请单
            $('#examRequest_back').click(function () {
                $('#examRequest_container').hide();

                if ($('#examRequest_container').attr('data-whoOpen') == 'examRequestResult_container' && $('#time_container').attr('data-whoOpen') == '') {
                    $('#examRequestResult_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                } else if(detailView == '1' && returnUrl) {
                    pageEvent.returnToUrl();
                } else if ($('#time_container').attr('data-whoOpen') == 'examRequestResult_container' && $('#examRequest_container').attr('data-whoOpen') == 'time_container') {
                    $('#examRequestResult_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                } else if ($('#time_container').attr('data-whoOpen') == 'unfinishedOfDetailView' && $('#examRequest_container').attr('data-whoOpen') == 'time_container') {
                    $('#time_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                }  else if ($('#examRequest_container').attr('data-whoOpen') == 'main_container') {
                    $('#main_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                } else {
                    $('#main_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                }
            });

            //关闭已预约申请单
            $('#examRequestResult_back').click(function () {
                $('#examRequestResult_container').hide();
                if (detailView == '1' && returnUrl) {
                    pageEvent.returnToUrl();
                } else {
                    $('#examRequestResult_container').show();
                    $('body').css({ 'background': '#f2f2f2' });
                }
            });

            //切换时间  
            $('#changeTime').change(function () {
                var $this = $(this);
                page.isScheduleTimeSelectPage = false;
                schedule.startDate = $this.val();
                schedule.days = 1;
                schedule.IgnoreScheduleFlag = true;
                schedule.getScheduleInfo(page.scheduleExamRequest, [], "", "", true, pageEvent.getScheduleInfoCallback, pageEvent.getScheduleInfoErrCallback);
            });
            //签到
            $('#main_container,#examRequestResult_container').on('click', '.sign', function () {
                var $this = $(this);
                if ($this.parents('#examRequestResult_container').length > 0) {
                    $('.sign_main').attr('data-whoOpen','examRequestResult_container');
                } else{
                    $('.sign_main').attr('data-whoOpen','main_container');
                }
                var placerOrderNO = $.trim($this.closest('.ifbook_items').data("placerorderno"));
                var observationUID = $.trim($this.closest('.ifbook_items').data("observationuid"));
                var serviceSectID = $.trim($this.closest('.ifbook_items').data("servicesectid"));
                var patientclass = $.trim($this.closest('.ifbook_items').data("patientclass"));
                var signStartDate = $.trim($this.closest('.ifbook_items').data("signstartdate"));
                var signEndDate = $.trim($this.closest('.ifbook_items').data("signenddate"));
                var scheduletime = $.trim($this.closest('.ifbook_items').data("signscheduletime"));
                var productName = $.trim($this.closest('.ifbook_rowdiv').find(".col-md-9").text());
                var userName = $.trim($("#unbook_show .b_name").text());
                var signStartMode = schedule.GetSysParameterValueByExamRequest({ ServiceSectID: serviceSectID, PatientClass: patientclass}, allowRegistByScheduleDateAheadMode);
                var signEndMode = schedule.GetSysParameterValueByExamRequest({ ServiceSectID: serviceSectID, PatientClass: patientclass }, allowRegistByScheduleDateLateMode);
                
                var examRequest = {};
                for (var i = 0, len = page.finishList.length; i < len; i++) {
                    if (placerOrderNO == $.trim(page.finishList[i].PlacerOrderNO)) {
                        examRequest = page.finishList[i];
                    }
                }
                $('#sign_main').attr('data-placerOrderNO', placerOrderNO);
                $('#sign_main').attr('data-observationUID', observationUID);
                $('#sign_main').attr('data-serviceSectID', serviceSectID);

                var mobileScheduleScanCodeCheckinResult = schedule.GetSysParameterValueByExamRequest(examRequest, mobileScheduleScanCodeCheckin);
                var mobileScheduleCheckinCodeResult = schedule.GetSysParameterValueByExamRequest(examRequest, mobileScheduleCheckinCode);
                //根据mobileScheduleDirectCheckin参数，是否隐藏直接签到菜单
                var mobileScheduleDirectCheckinResult = schedule.GetSysParameterValueByExamRequest(examRequest, mobileScheduleDirectCheckin);
                var showBtnThan1 = (mobileScheduleScanCodeCheckinResult == "1" && mobileScheduleCheckinCodeResult == "0" && mobileScheduleDirectCheckinResult == "0")
                    || (mobileScheduleScanCodeCheckinResult == "0" && mobileScheduleCheckinCodeResult == "1" && mobileScheduleDirectCheckinResult == "0")
                    || (mobileScheduleScanCodeCheckinResult == "0" && mobileScheduleCheckinCodeResult == "0" && mobileScheduleDirectCheckinResult == "1");
                var showSigndiv = function () {
                    if (showBtnThan1) {
                        if (mobileScheduleScanCodeCheckinResult == "1") { 
                            pageEvent.scanCode();
                        } else if (mobileScheduleCheckinCodeResult == "1") {
                            pageEvent.signCode($('.sign_main').find('.code'));
                        } else if (mobileScheduleDirectCheckinResult == "1") {
                            pageEvent.signDirect();
                        }
                    } else {
                        $('.sign_main').show();
                        var sign_div_center_h = $(".sign_div_center").height();
                        sign_div_center_h = sign_div_center_h == "" ? 0 : sign_div_center_h;
                        $(".sign_div_center").css("bottom", ($(window).height()) / 2 - sign_div_center_h / 2 + "px");
                        if (mobileScheduleScanCodeCheckinResult != 1) {
                            $('.sign_main').find('.scan_code').hide();
                        } else {
                            $('.sign_main').find('.scan_code').show();
                        }
                        if (mobileScheduleCheckinCodeResult == "1") {
                            $('.sign_main').find('.code').show();
                        } else {
                            $('.sign_main').find('.code').hide();
                        }

                        if (mobileScheduleDirectCheckinResult != 1) {
                            $('.sign_main').find('.sign_direct').hide();
                        } else {
                            $('.sign_main').find('.sign_direct').show();
                        }
                    }
                }

                if (!checkinRight) {
                    schedule.alert("您没有签到的权限！");
                    return;
                }

                if (checkinRightConfig.length > 0 && checkinRightConfig.indexOf(serviceSectID) == -1) {
                    schedule.alert('您没有' + serviceSectID + '的签到权限！');
                    return;
                }

                //判断是否可以签到
                var signMsg = userName + '-' + serviceSectID + '-' + productName + ' ：<br/>签到时间范围：' + scheduletime + '。<br />当前签到时间不在允许签到时间范围内。';
                if ($.trim(allowRegistByScheduleDateAhead) != "" && signStartMode != "2" && new Date() < new Date(signStartDate + ":00")) {
                    schedule.alert(signMsg);
                    return;
                }
                if ($.trim(allowRegistByScheduleDateLate) != "" && signEndMode != "2" && new Date() >= new Date(signEndDate + ":00")) {
                    schedule.alert(signMsg);
                    return;
                }

                var tips = imcis.schedule.getSysParamValue(checkTips, serviceSectID);
                if (tips) {
                    schedule.comfirm(tips, showSigndiv);
                } else {
                    showSigndiv();
                }
            });
            //签到扫码取消
            $('body').on('click', '.code_cancle', function () {
                $('.sign_main').hide();
            });
            //扫码
            $('body').on('click', '.scan_code', function () {
                pageEvent.scanCode();
            });

            //直接签到
            $('body').on('click', '.sign_direct', function () {
                pageEvent.signDirect();
            });

            //签到码
            $('body').on('click', '.code,.sign-code', function () {
                pageEvent.signCode($(this));
            });
        },
        isAndroid: function () {
            var u = navigator.userAgent;
            if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
                return true;
            }
            return false;
        },
        //黑名单限制及提示
        scheduleLimit: function () {
            var $this = this;
            var notEditType = $($this).attr("data-notEditType");
            var notCancelType = $($this).attr("data-notCancelType");
            switch (notEditType) {
                case "allowSelfEditTimes":
                    var times = $($this).attr("data-editTimes");
                    schedule.alert(`自助预约已超过${times}次，如有需要请联系相关科室。`);
                    break;
                case "allowUpdateSchedule":
                    var times = $($this).attr("data-allowUpdateTimes");
                    var scheduleStartDate = $($this).attr("data-ScheduleStartDate");
                    var resultStatus = $($this).attr("data-resultStatus");
                    var patientClass = $($this).attr("data-patientClass");
                    var serviceSectID = $($this).attr("data-serviceSectID");
                    var scheduleRoute = $($this).attr("data-scheduleRoute");
                    var tip = $.trim(resultStatus) == "" ?
                        `预约开始时间${scheduleStartDate}前${times != null ? times : ""}分钟不允许自助修改，如有需要请联系相关科室。` :
                        `检查状态=${resultStatus}的${serviceSectID}、${patientClass}、${scheduleRoute}不允许自助修改，如有需要请联系相关科室。`;
                    schedule.alert(tip);
                    break;
            }

            switch (notCancelType) {
                case "allowSelfCancelTimes":
                    var times = $($this).attr("data-cancelTimes");
                    schedule.alert(`自助取消预约已超过${times}次，如有需要请联系相关科室。`);
                    break;
                case "allowCancelSchedule":
                    var times = $($this).attr("data-allowCancelTimes");
                    var scheduleStartDate = $($this).attr("data-ScheduleStartDate");
                    schedule.alert(`预约开始时间${scheduleStartDate}前${times != null ? times : ""}分钟不允许自助取消，如有需要请联系相关科室。`);
                    break;
                case "cancelResultStatus":
                    var resultStatus = $($this).attr("data-resultStatus");
                    var patientClass = $($this).attr("data-patientClass");
                    var serviceSectID = $($this).attr("data-serviceSectID");
                    var scheduleRoute = $($this).attr("data-scheduleRoute");
                    schedule.alert(`检查状态=${resultStatus}的${serviceSectID}、${patientClass}、${scheduleRoute}不允许自助取消，如有需要请联系相关科室。`);
                    break;
            }

            if (scheduleLimit != "" && scheduleLimit != "0") {
                if (limitMsg != "")
                    schedule.alert(limitMsg.replace(/\\n/g, '<br/>'));
                if (scheduleLimit != "1")
                    return true;
            }
            return false;
        },
        //计算两个经纬度的距离(千米)
        getDistance: function (lng1, lat1, lng2, lat2){
            var toRadians = function (degre) {
                return degre * Math.PI / 180;
            };

            var r = 6371; //地球半径
            var deltaLatitude = toRadians(lat2 - lat1);
            var deltaLongitude = toRadians(lng2 - lng1);
            lat1 = toRadians(lat1);
            lat2 = toRadians(lat2);

            var a = Math.sin(deltaLatitude / 2) *
                Math.sin(deltaLatitude / 2) +
                Math.cos(lat1) *
                Math.cos(lat2) *
                Math.sin(deltaLongitude / 2) *
                Math.sin(deltaLongitude / 2);

            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            var d = r * c;
            return d;
        },
        //位置服务
        getLocationBywx: function (callback) {
            wx.ready(function () {
                wx.checkJsApi({
                    jsApiList: ['getLocation'],
                    success: function (res) {
                        //信息格式：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                        if (res.checkResult.getLocation == false) {
                            schedule.alert('微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                            return;
                        }
                        wx.getLocation({
                            type: 'wgs84',						    // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                            success: function (res) {
                                try {
                                    console.log("微信data" + res);
                                    var speed = res.speed; 			// 速度，以米/每秒计
                                    var accuracy = res.accuracy; 	// 位置精度
                                    var latitude = res.latitude; 	// 纬度，浮点数，范围为90 ~ -90
                                    var longitude = res.longitude;  // 经度，浮点数，范围为180 ~ -180。

                                    callback(longitude, latitude);
                                } catch (error) {
                                    schedule.alert('获取地理位置失败。');
                                }
                            },
                            cancel: function (res) {
                                schedule.alert('用户拒绝授权获取地理位置。');
                            },
                            fail: function (res) {
                                alert("未能获取地理位置，首先检查手机是否启用微信定位");
                            }
                        });
                    }
                });
            });
        },
        getLocationBynav: function (callback) {
            var successfulCallback = function (position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                var accuracy = position.coords.accuracy;
                imcis.wait.end();
                if (accuracy >= 500) {
                    schedule.alert("无法精确定位！");
                } else {
                    callback(longitude, latitude);
                }
            }

            var failCallback = function (error) {
                var text;
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        text = "用户拒绝对获取地理位置的请求。";
                        break;
                    case error.POSITION_UNAVAILABLE:
                        text = "位置信息是不可用的。";
                        break;
                    case error.TIMEOUT:
                        text = "请求用户地理位置超时。";
                        break;
                    case error.UNKNOWN_ERROR:
                        text = "未知错误。";
                        break;
                }
                imcis.wait.end();
                schedule.alert(text);
            }

            //判断浏览器是否支持HTML5 定位
            if (window.navigator.geolocation) {
                imcis.wait.start();
                var options = {
                    enableHighAccuracy: true,
                    timeout: 5000,
                    maximumAge: 1000
                };
                navigator.geolocation.getCurrentPosition(successfulCallback, failCallback, options);
            } else {
                schedule.alert("你的浏览器不能使用HTML5定位");
            }
        },
        getLocation: function (callback) {
            if (_longitude > 0 && _latitude > 0) {  //请求传入当前经纬度模式
                callback(_longitude, _latitude);
            } else if (appId != "" && access_token != "") {    //微信js接口返回位置信息
                pageEvent.getLocationBywx(callback);
            } else {    //根据浏览器接口获取位置信息
                pageEvent.getLocationBynav(callback);
            }
        },
        signDirect: function () {
            var serviceSectID = $('#sign_main').attr('data-serviceSectID');
            var signDirect = function () {
                var placerOrderNO = $('#sign_main').attr('data-placerOrderNO');
                var observationUID = $('#sign_main').attr('data-observationUID');
                imcis.ajax(schedule.relativeUrl + "Checkin", {
                    placerOrderNO: placerOrderNO,
                    observationUID: observationUID,
                    scheduleRoute: scheduleRoute || 5
                }, true, function (ret) {
                    if (ret && ret.Success) {
                        schedule.alert("签到成功。");

                        if ($('.sign_main').attr('data-whoOpen') == 'examRequestResult_container') {
                            $('.sign').hide();
                            $('.sign_main').hide();
                        } else {
                            $('.ifbook_items[data-observationuid="' + observationUID + '"]').find('.attation').html("登记完成").width(86);
                            $('.ifbook_items[data-observationuid="' + observationUID + '"]').find('.book_pop').remove();
                            $('.finish-container,.un-finish-container,.finish-sign').html('');

                            page.finishList = [],
                                page.unFinishList = [];
                            page.signList = [];
                            schedule.getExamRequestList(page.getExamRequestListCallback, 'SignFinish');
                            $('.sign_main').hide();
                            //跳转掉签到
                            $('#main_container .b-container').height($(window).height() - 90);
                            $('#unbook_title').removeClass('ifactived');
                            $('#book_title').removeClass('ifactived');
                            $('#sign').addClass('ifactived');
                            $('.un-finish-container').hide();
                            $('#saveMulti').hide();
                            $('.finish-container').hide();
                            $('.finish-sign').show();
                        }
                    } else {
                        $('.sign_main').hide();
                        schedule.alert(ret.ErrorMsg);
                    }
                }, function () {
                    $('.sign_main').hide();
                    schedule.alert("签到失败，请重试。");
                });
            };

            var scheduleDirectCheckinLocation = schedule.GetSysParameterValueByExamRequest({ ServiceSectID: serviceSectID, PatientClass: '' }, mobileScheduleDirectCheckinLocation);
            var sysParams = scheduleDirectCheckinLocation.split(",");
            var point = sysParams[0].split("-");
            if (point[0] == "") {
                signDirect();
            } else {
                var latitude = parseFloat(point[0]), longitude = parseFloat(point[1]);
                var range = sysParams.length > 1 ? parseFloat(sysParams[1]) : 0;
                //120.14237960388697, 30.280233213923292
                pageEvent.getLocation(function (long, lat) {
                    var distance = pageEvent.getDistance(longitude, latitude, long, lat) * 1000;
                    if (distance.toFixed(2) > range) {
                        schedule.alert("超出签到范围，无法签到！");
                    } else {
                        signDirect();
                    }
                });
            }
        },
        signCode: function ($this) {
            var url = $this.data('url');
            if ($('.sign_main').attr('data-whoOpen') == 'examRequestResult_container') {
                $('#attantion_title').text('签到码');
                $('#examRequestResult_container,.sign_main').hide();
                $('#attantion_container').attr('data-whoOpen', 'examRequestResult_container');
            } else {
                $('#main_container,.sign_main').hide();
                if ($(".ifactived").attr('id') == 'book_title') { $('#attantion_title').text('签到码'); } else { $('#attantion_title').text('结果码'); }
            }
            $('#attion_main').text('');
            $('#attantion_container,#sign_main').show();
            $('body').css({ 'background': '#fff' });
            var observationUID = $this.attr('data-observationUID') || $('#sign_main').attr('data-observationUID');
            var placerOrderNO = $('#sign_main').attr('data-placerOrderNO');
            if (!observationUID) {
                $.each(page.finishList, function (i, n) {
                    if (placerOrderNO == n.PlacerOrderNO) {
                        observationUID = n.ObservationUID;
                        return false;
                    }
                });
            }

            $('#sign_main img').attr('src', url + "?observationUID=" + observationUID + "&t=" + imcis.date.now());
        },
        scanCode: function () {
            if (!isWeixin) {
                $('.sign_main').hide();
                schedule.alert("非微信环境不支持扫码。");
                return;
            }
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果

                    if (result) {
                        var rlist = result.split('&');
                        if (rlist.length == 2) {
                            var timestamp = rlist[0].split('=')[1];
                            var token = rlist[1].split('=')[1];
                            var placerOrderNO = $('#sign_main').attr('data-placerOrderNO');
                            var observationUID = $('#sign_main').attr('data-observationUID');
                            imcis.ajax(schedule.relativeUrl + "AutoRegister", {
                                placerOrderNO: placerOrderNO,
                                observationUID: observationUID,
                                scheduleRoute: scheduleRoute || 5,
                                timestamp: timestamp,
                                token: token
                            }, true, function (ret) {
                                if (ret && ret.Success) {
                                    schedule.alert("签到成功。");
                                    if ($('.sign_main').attr('data-whoOpen') == 'examRequestResult_container') {
                                        $('.sign').hide();
                                        $('.sign_main').hide();
                                    } else {
                                        $('.ifbook_items[data-observationuid="' + observationUID + '"]').find('.attation').html("登记完成").width(86);
                                        $('.ifbook_items[data-observationuid="' + observationUID + '"]').find('.book_pop').remove();
                                        $('.finish-container,.un-finish-container,.finish-sign').html('');

                                        page.finishList = [],
                                            page.unFinishList = [];
                                        page.signList = [];
                                        schedule.getExamRequestList(page.getExamRequestListCallback, 'SignFinish');
                                        $('.sign_main').hide();
                                        //跳转掉签到
                                        $('#main_container .b-container').height($(window).height() - 90);
                                        $('#unbook_title').removeClass('ifactived');
                                        $('#book_title').removeClass('ifactived');
                                        $('#sign').addClass('ifactived');
                                        $('.un-finish-container').hide();
                                        $('#saveMulti').hide();
                                        $('.finish-container').hide();
                                        $('.finish-sign').show();
                                    }

                                } else {
                                    $('.sign_main').hide();
                                    schedule.alert(ret.ErrorMsg);
                                }
                            }, function () {
                                $('.sign_main').hide();
                                schedule.alert("签到失败，请重试。");
                            });
                        } else {
                            $('.sign_main').hide();
                            schedule.alert("二维码错误。");
                        }
                    } else {
                        $('.sign_main').hide();
                        schedule.alert("扫码失败，请重新扫码。");
                    }
                },
                fail: function (res) {
                    $('.sign_main').hide();
                    schedule.alert("调用微信扫一扫失败，" + res.errorMsg);
                }
            });
        },
        returnToUrl:function(){
            if(returnUrl.indexOf('?') < 0) {
                returnUrl += '?';
            }

            returnUrl += '&ResultCode=' + (page.scheduleExamRequest.ResultCode || '0')
                       + '&ScheduleStartDate=' + encodeURIComponent(page.scheduleExamRequest.ScheduleStartDate)
                       + '&ScheduleEndDate='  + encodeURIComponent(page.scheduleExamRequest.ScheduleEndDate)
                       + '&ScheduleID=' + encodeURIComponent(page.scheduleExamRequest.ScheduleID)
                       + '&ScheduleResourceLocation=' + encodeURIComponent(page.scheduleExamRequest.ResourceLocation);

            location.href = returnUrl;
        },

        //显示检查申请
        showUnFinish: function () {
            $('.sign_main').hide();
            $('#main_container .b-container').height($(window).height() - 90);
            if (scheduleSelfShowSaveMultiButton) {
                $('#main_container  .un-finish-container').css({ 'height': $(window).height() - 115 });
            }
            $('#unbook_title').addClass('ifactived');
            $('.un-finish-container').show();
            $('#book_title').removeClass('ifactived');
            $('.finish-container').hide();
            $('#sign').removeClass('ifactived');
            $('.finish-sign').hide();
            page.updateStatus(true);
        },

        //显示已预约
        showFinish: function () {
            $('#main_container .b-container').height($(window).height() - 90);
            $('#unbook_title').removeClass('ifactived');
            $('.un-finish-container').hide();
            $('#book_title').addClass('ifactived');
            $('.finish-container').show();
            $('#sign').removeClass('ifactived');
            $('.finish-sign').hide();
            page.updateStatus(true);
            $('#saveMulti').hide();
        },

        //显示已签到
        showSign: function () {
            $('#main_container .b-container').height($(window).height() - 90);
            $('#unbook_title').removeClass('ifactived');
            $('#book_title').removeClass('ifactived');
            $('#sign').addClass('ifactived');
            $('.un-finish-container').hide();
            $('#saveMulti').hide();
            $('.finish-container').hide();
            $('.finish-sign').show()
            page.updateStatus(true);
        },
        //取消预约
        cancelSchedule: function () {
            var $this = $(this);
            var scheduletime = $this.closest('.ifbook_items').data("scheduletime").substr(0, 16);
            var serviceSectID = $this.closest('.ifbook_items').data("servicesectid");
            var result = schedule.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead(scheduletime, serviceSectID, ScheduleAutoNotAllowCancelByScheduleDateAhead, "Cancel");
            if (result == false) {
                return;
            }
            var exam = {};
            var index = 0;
            var placerOrderNO = $this.closest('.ifbook_items').data("placerorderno");
            $.each(page.finishList, function (i, n) {
                if (n.PlacerOrderNO == placerOrderNO) {
                    exam = n;
                    index = i;
                }
            });

            var cancelSchedule = function (scheduleBreakFlag, tips) {
                schedule.comfirm(tips, function () {
                    schedule.cancelSchedule({
                        'PlacerOrderNO': placerOrderNO,
                        'ScheduleRoute': scheduleRoute || 5,
                        'ScheduleBreakFlag': scheduleBreakFlag,
                        'OrganizationID': exam.OrganizationID,
                        'ScheduleOrderFlag': exam.ScheduleOrderFlag
                    }, function (data) {
                        if (detailView == '1' && $this.parents('#examRequestResult_container').length > 0) {
                            var item = $this.closest('.ifbook_items');
                            item.find('.scheduletime').text('');
                            item.find('.observationlocation').text('');
                        } else {
                            $this.closest('.ifbook_items').remove();
                            exam.ScheduleFlag = false;
                            exam.ChangeFlag = false;
                            exam.ScheduleStatus = 1;
                            if(exam.ScheduleOrderFlag == '2') {
                                exam.ScheduleOrderFlag = '0';
                            }
                            //操作成功，取消次数加1
                            exam.SelfCancelTimes = exam.SelfCancelTimes == null ? 1 : exam.SelfCancelTimes++;

                            if (exam.orderList && exam.orderList.length > 0) {
                                for (var j = 0; j < exam.orderList.length; j++) {
                                    exam.orderList[j].ScheduleFlag = false;
                                    exam.orderList[j].ChangeFlag = false;
                                    exam.orderList[j].ScheduleStatus = 1;
                                    if(exam.orderList[j].ScheduleOrderFlag == '2') {
                                        exam.orderList[j].ScheduleOrderFlag = '0';
                                    }
                                }
                            }

                            /*
                            page.finishList.splice(index, 1);

                            //待预约数据状态为已签到的在已签到显示
                            var signInStatus = schedule.GetSysParameterValueByExamRequest(list[i], signInCompletedByResultStatus);
                            if (signInStatus.indexOf(exam.ResultStatus) == -1) {
                                page.unFinishList.push(exam);
                                page.bindUnFinish(exam, "cancel");
                            } else {
                                page.signList.push(exam);
                                page.bindSign(exam);
                            }

                            page.updateStatus();
                            */
                            page.unFinishList.push(exam);
                            page.finishList.splice(index, 1);

                            page.bindUnFinish(exam, "cancel");
                            page.updateStatus();

                            if (page.finishList.length === 0) {
                                pageEvent.showUnFinish();
                            } else {
                                $('#saveMulti').hide();
                            }
                            return false;
                        }
                    });
                });
            };

            //exam添加ScheduleStartTimeDetail、ScheduleEndTimeDetail
            if (typeof exam.orderList != "undefined") {
                exam.ScheduleStartTimeDetail = imcis.convertDateFromJson(exam.orderList[0].ScheduleStartTimeDetail);
                exam.ScheduleEndTimeDetail = imcis.convertDateFromJson(exam.orderList[0].ScheduleEndTimeDetail);
            }

            var tipStr = "确定取消预约？";
            var allowTimes = $this.attr("data-allowTimes");
            if ($.trim(allowTimes) != "") {
                var surplusTimes = parseInt(allowTimes) - (exam.SelfCancelTimes == null ? 0 : exam.SelfCancelTimes);
                if (surplusTimes > 0) {
                    tipStr = `自助取消预约剩余${surplusTimes}次，请谨慎取消。<br>确定取消预约？`;
                } else {
                    schedule.alert(`自助取消预约已超过${allowTimes}次，如有需要请联系相关科室。`);
                    $this.removeClass("edit_book").addClass("unedit_book").find("span").html("不提供取消");
                    return false;
                }
            }

            //爽约
            var cancelScheduleDate = schedule.GetSysParameterValueByExamRequest2(exam, scheduleBreakCancelByScheduleDateAhead);
            if (cancelScheduleDate != "") {
                if (new Date() >= new Date(schedule.GetDateByExamAndParam(exam, cancelScheduleDate) + ":00")) {
                    var tips = schedule.GetSysParameterValueByExamRequest2(exam, scheduleBreakCancelTip);
                    if (tips != "") {
                        cancelSchedule(true, "取消预约会被记录为爽约！<br/>" + tips);
                    } else {
                        cancelSchedule(true, tipStr);
                    }
                } else {
                    cancelSchedule(false, tipStr);
                }
            } else {
                cancelSchedule(false, tipStr);
            }
        },

        //修改预约时
        editSchedule: function () {
            var $this = $(this);
            if ($this.parents('#examRequestResult_container').length > 0) {
                $('#time_container').attr('data-whoOpen', 'examRequestResult_container');
                $('#examRequestResult_container').hide();
            }

            var scheduletime = $this.closest('.ifbook_items').data("scheduletime").substr(0, 16);
            var serviceSectID = $this.closest('.ifbook_items').data("servicesectid");
            var result = schedule.ScheduleAutoNotAllowCancelOrEditByScheduleDateAhead(scheduletime, serviceSectID, ScheduleAutoNotAllowEditByScheduleDateAhead, "Edit");
            if (result == false)
            {
                return;
            }
            page.saveType = 1;
            
            var placerOrderNO = $(this).closest('.ifbook_items').data('placerorderno');
            $.each(page.finishList, function (i, n) {
                if (n.PlacerOrderNO == placerOrderNO) {
                    var allowTimes = $this.attr("data-allowTimes");
                    if ($.trim(allowTimes) != "") {
                        var surplusTimes = parseInt(allowTimes) - (n.SelfEditTimes == null ? 0 : n.SelfEditTimes);
                        if (surplusTimes > 0) {
                            schedule.alert(`自助预约剩余${surplusTimes}次，请谨慎修改。`);
                        } else {
                            schedule.alert(`自助预约已超过${allowTimes}次，如有需要请联系相关科室。`);
                            $this.addClass("unedit_book").find("span").html("不提供修改");
                            return false;
                        }
                    }

                    page.scheduleExamRequestOld = JSON.parse(JSON.stringify(n));
                    pageEvent.showDetailView(n, false);
                    return false;
                }
            });
        },

        //开始预约
        startSchedule: function () {
            if (scheduleLimit != "1" && pageEvent.scheduleLimit()) {
                return false;
            }
            var $this = $(this);
            if ($this.data('self') == "0") {
                pageEvent.showNotScheduleMemo($(this), page.unFinishList);
            } else {
                page.saveType = 0;

                var placerOrderNO = $(this).closest('.ifbook_items').data('placerorderno');
                $.each(page.unFinishList, function (i, n) {
                    if (n.PlacerOrderNO == placerOrderNO) {
                        pageEvent.showDetailView(n,false);
                        return false;
                    }
                });
            }
        },

        showDetailView: function (n, isDirectComingByDetailView) {
            function showTimeContainer() {
                //接口进入预约详情页面，ReturnUrl为空，则不显示返回按钮，
                if (!returnUrl && $('#time_container').attr('data-whoOpen') == 'unfinishedOfDetailView') {
                    $('#backToMain').off();
                    $('#backToMain').css({ 'display': 'none' });
                    $('#save_time').css({ 'right': '5%', 'left': '5%', 'width': '90%' });
                }
                $('.ServiceSectID').text(n.ServiceSectID);
                $('.ProcedureName').text(n.ProcedureName);
                
                var now = new Date();
                schedule.startDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
                schedule.localSartDate = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate();
                schedule.days = 1;
                schedule.IgnoreScheduleFlag = true;
                schedule.getScheduleInfo(n, [], "", "", true, pageEvent.getScheduleInfoCallback, pageEvent.getScheduleInfoErrCallback);
            }

            //直接通过DetailView=1进来
            if (isDirectComingByDetailView) {
                pageEvent.judgingMobileScheduleCheckinInterface([n]);//是否显示签到界面
                if (n.ScheduleFlag && scheduleCompletedByResultStatus && scheduleCompletedByResultStatus.indexOf(n.ResultStatus) > -1 && pageEvent.judgingExamRequestMatchResultStatus(n)) {
                    page.finishList.push(n);
                    page.bindFinishForDetailView(n);
                } else if (!n.ScheduleFlag && !n.NeedScheduleFlag) {
                    page.unFinishList.push(n);
                    page.bindUnFinishForDetailView(n);
                } else {
                    $('#time_container').show();
                    $('#time_container').attr('data-whoOpen', 'unfinishedOfDetailView');
                    showTimeContainer();
                }
            } else {
                showTimeContainer()
            }
            
            page.scheduleExamRequest = n;
        },

        //手机端预约有返回地址时预约及保存后提示信息
        returnUrlTipsAfterSave: function () {
            if ($.trim(returnUrlTipsAfterSave) == "" || $.trim(returnUrl) == "")
                return false;

            schedule.comfirm(returnUrlTipsAfterSave, function () {
                pageEvent.returnToUrl();
            });
        },

        //保存单个预约
        saveExamSchedule: function () {
            var $this = $(this);
            if (!page.saveExamScheduleFlag) {
                page.saveExamScheduleFlag = true;
            } else {
                return;
            }

            if(page.scheduleExamRequest.ScheduleFlag && !page.scheduleExamRequest.ChangeFlag){
                page.saveExamScheduleFlag = false;
                return;
            }

            var promptDetail = $this.data('promptdetail') || '';
            if(promptDetail == "1" || (promptDetail == "2" && page.scheduleExamRequest.ScheduleStatus === 0)) {
                promptDetail = "预约时间" + page.scheduleExamRequest.ScheduleStartDate + '-' + page.scheduleExamRequest.ScheduleEndDate.substring(11) + "。";
            } else {
                promptDetail = "";
            }

            if(page.scheduleExamRequest.PregnantDays){
                var pregnantWeek = $('#time_isbook .selected_day .pregnantWeek').text();
                if(pregnantWeek) {
                    promptDetail += '检查当日' + pregnantWeek + "。";
                }
            }

            //修改预约爽约提醒
            if (page.saveType == 1) {
                page.scheduleBreakFlag = false; //恢复成false
                if (typeof page.scheduleExamRequestOld.orderList != "undefined") {
                    page.scheduleExamRequestOld.ScheduleStartTimeDetail = imcis.convertDateFromJson(page.scheduleExamRequestOld.orderList[0].ScheduleStartTimeDetail);
                    page.scheduleExamRequestOld.ScheduleEndTimeDetail = imcis.convertDateFromJson(page.scheduleExamRequestOld.orderList[0].ScheduleEndTimeDetail);
                }
                var editScheduleDate = schedule.GetSysParameterValueByExamRequest2(page.scheduleExamRequestOld, scheduleBreakEditByScheduleDateAhead);
                if (editScheduleDate != "") {
                    if (new Date() >= new Date(schedule.GetDateByExamAndParam(page.scheduleExamRequestOld, editScheduleDate) + ":00")) {
                        page.scheduleBreakFlag = true;
                        var tips = schedule.GetSysParameterValueByExamRequest2(page.scheduleExamRequestOld, scheduleBreakEditTip);
                        if (tips != "")
                            promptDetail = "修改预约会被记录为爽约！<br/>" + tips;
                    }
                }
            }

            if(promptDetail){
                schedule.comfirm(promptDetail + '确认预约？', function () {
                    pageEvent.saveExamScheduleExecute($this);
                }, function(){
                    page.saveExamScheduleFlag = false;
                });
            } else {
                pageEvent.saveExamScheduleExecute($this);
            }
        },

        saveExamScheduleExecute: function($this){
            page.scheduleExamRequest.ScheduleRoute = scheduleRoute || 5;

            schedule.saveExamSchedule(page.scheduleExamRequest, page.scheduleBreakFlag, function (data, writebackFailList) {
                var placerOrderNO = page.scheduleExamRequest.PlacerOrderNO;
                var alertReceiptFlag = false;
                //根据参数是否弹出申请单
                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        var n = data[i];
                        if (placerOrderNO == n.PlacerOrderNO) {
                            page.scheduleExamRequest.ScheduleResourceUID = n.ScheduleResourceUID;
                            page.scheduleExamRequest.ScheduleResourceName = n.ScheduleResourceName;
                            page.scheduleExamRequest.ScheduleStartDate = n.ScheduleStartDate;
                            page.scheduleExamRequest.ScheduleEndDate = n.ScheduleEndDate;
                            page.scheduleExamRequest.ScheduleTimeDetail = n.ScheduleTimeDetail;
                            page.scheduleExamRequest.ScheduleStartTimeDetail = n.ScheduleStartTimeDetail;
                            page.scheduleExamRequest.ScheduleEndTimeDetail = n.ScheduleEndTimeDetail;
                            page.scheduleExamRequest.ResourceLocation = n.ResourceLocation;
                            page.scheduleExamRequest.ScheduleFlag = true;
                            page.scheduleExamRequest.ScheduleStatus = 0;
                            page.scheduleExamRequest.ObservationUID = n.ObservationUID;
                            page.scheduleExamRequest.ResultCode = 1;
                            page.scheduleExamRequest.ScheduleRoute = scheduleRoute || 5;
                            //操作成功，修改次数加1
                            page.scheduleExamRequest.SelfEditTimes = page.scheduleExamRequest.SelfEditTimes == null ? 1 : page.scheduleExamRequest.SelfEditTimes++;
                            if (mobileScheduleSuccessShowReceipt && mobileScheduleSuccessShowReceipt.trim() == "1") {
                                alertReceiptFlag = true;
                                pageEvent.alertExamRequest(page.scheduleExamRequest,$this);
                            }

                            var detailTips = schedule.GetSysParameterValueByExamRequest(page.scheduleExamRequest, mobileScheduleSuccessDetailTips);
                            if(detailTips == '1') {
                                var str = '预约完成' + 
                                          '<div style="text-align: left;">' + 
                                              '检查类型：' +  n.ServiceSectID + '<br/>' +
                                              '检查部位：' + n.ProcedureName + '<br/>';

                                var showTimeType = schedule.GetSysParameterValueByExamRequest(n, mobileScheduleShowTimeType);
                                switch (showTimeType) {
                                    case '1':
                                        if(n.ScheduleTimeDetail) {
                                            str += "预检时间：" + n.ScheduleStartDate.substring(0, 10) + ' ' + n.ScheduleTimeDetail;
                                        } else {
                                            str += "预约时间：" + n.ScheduleStartDate + '-' + n.ScheduleEndDate.substring(11);
                                        }
                                        break;
                                    case '2':
                                        str += "预约时间：" + n.ScheduleStartDate
                                        break;
                                    case '3':
                                        if(n.ScheduleTimeDetail) {
                                            str += "预检时间：" + n.ScheduleStartDate.substring(0, 10) + ' ' + n.ScheduleTimeDetail.split('-')[0];
                                        } else {
                                            str += "预约时间：" + n.ScheduleStartDate;
                                        }
                                        break;
                                    case '4':   //签到时间范围 开始时间  allowRegistByScheduleDateAhead  结束时间  allowRegistByScheduleDateLate
                                        var startDate4 = page.getDateByParameters(n, n.ScheduleStartDate, allowRegistByScheduleDateAhead);
                                        var endDate4 = page.getDateByParameters(n, n.ScheduleEndDate, allowRegistByScheduleDateLate);
                                        str += "签到时间：" + startDate4.substr(0, 16) + "-" + endDate4.substr(11, 5);
                                        break;
                                    case '5':   //签到开始时间
                                        str += "签到时间：" + page.getDateByParameters(n, n.ScheduleStartDate, allowRegistByScheduleDateAhead);
                                }

                                str += '</div>';
                                schedule.alert(str);
                            }
                        }
                    }
                } else if(writebackFailList && writebackFailList.length > 0) {
                    if (mobileScheduleSuccessShowReceipt && mobileScheduleSuccessShowReceipt.trim() == "1") {
                        schedule.comfirmOnlyYes('预约登记异常，无法自动跳转到回执单页面！', function () {
                            if (!returnUrl && !alertReceiptFlag && $('#time_container').attr('data-whoOpen') == 'examRequestResult_container') {
                                location.reload();
                            }
                        });
                    }
                } else {
                    if (!returnUrl && !alertReceiptFlag && $('#time_container').attr('data-whoOpen') == 'examRequestResult_container') {
                        location.reload();
                    }
                    
                    return;
                }

                if (detailView == '1') {
                    if (!returnUrl && !alertReceiptFlag && $('#time_container').attr('data-whoOpen') == 'examRequestResult_container') {
                        location.reload();
                    } else if(returnUrl  && !alertReceiptFlag) {
                        pageEvent.returnToUrl();
                    } else {
                        $('.schedule-finish').removeClass('schedule-finish').addClass('schedule-enable');
                        $('.schedule-current').removeClass('schedule-current').addClass('schedule-finish');
                    }

                } else {
                    //检查申请的保存
                    if (page.saveType == 0) {
                        $('.ifbook_items[data-PlacerOrderNO="' + placerOrderNO + '"]').remove();
                        $.each(page.unFinishList, function (i, n) {
                            if (n.PlacerOrderNO == placerOrderNO) {
                                page.finishList.push(page.scheduleExamRequest);
                                page.bindFinish(page.scheduleExamRequest);
                                page.unFinishList.splice(i, 1);
                                page.updateStatus();
                                if (page.unFinishList.length === 0) {
                                    pageEvent.showFinish();
                                }

                                return false;
                            }
                        });
                    } else {
                        //已预约的修改
                        $.each(page.unFinishList, function (i, n) {
                            if (n.PlacerOrderNO == placerOrderNO) {
                                n.ScheduleResourceUID = page.scheduleExamRequest.ScheduleResourceUID;
                                n.ScheduleResourceName = page.scheduleExamRequest.ScheduleResourceName
                                n.ScheduleStartDate = page.scheduleExamRequest.ScheduleStartDate;
                                n.ScheduleEndDate = page.scheduleExamRequest.ScheduleEndDate;
                                n.ScheduleTimeDetail = page.scheduleExamRequest.ScheduleTimeDetail;
                                n.ScheduleStartTimeDetail = page.scheduleExamRequest.ScheduleStartTimeDetail;
                                n.ScheduleEndTimeDetail = page.scheduleExamRequest.ScheduleEndTimeDetail;
                                n.SelfEditTimes = page.scheduleExamRequest.SelfEditTimes == null ? 0 : page.scheduleExamRequest.SelfEditTimes;

                                var startDate = imcis.convertDateFromJson(n.ScheduleStartDate);
                                var endDate = imcis.convertDateFromJson(n.ScheduleEndDate);
                                var startTimeDetail = imcis.convertDateFromJson(n.ScheduleStartTimeDetail);
                                var endTimeDetail = imcis.convertDateFromJson(n.ScheduleEndTimeDetail);
                                var scheduleTime = startDate.substr(0, 16) + "-" + endDate.substr(11, 5);
                                var showTimeType = schedule.GetSysParameterValueByExamRequest(n, mobileScheduleShowTimeType);
                                switch (showTimeType) {
                                    case '1':
                                        if (n && n.ScheduleStartTimeDetail) {
                                            scheduleTime = startTimeDetail.substr(0, 16) + "-" + endTimeDetail.substr(11, 5);
                                        }
                                        break;
                                    case '2':
                                        scheduleTime = startDate;
                                        break;
                                    case '3':
                                        if (n && n.ScheduleStartTimeDetail) {
                                            scheduleTime = startTimeDetail;
                                        } else {
                                            scheduleTime = startDate;
                                        }
                                        break;
                                    case '4':   //签到时间范围 开始时间  allowRegistByScheduleDateAhead  结束时间  allowRegistByScheduleDateLate
                                        scheduleTimeTitle = "签到时间";
                                        var startDate4 = page.getDateByParameters(n, startDate, allowRegistByScheduleDateAhead);
                                        var endDate4 = page.getDateByParameters(n, endDate, allowRegistByScheduleDateLate);
                                        scheduleTime = startDate4.substr(0, 16) + "-" + endDate4.substr(11, 5);
                                        break;
                                    case '5':   //签到开始时间
                                        scheduleTimeTitle = "签到时间";
                                        scheduleTime = page.getDateByParameters(n, startDate, allowRegistByScheduleDateAhead);
                                }

                                var $item = $('.ifbook_items[data-PlacerOrderNO="' + placerOrderNO + '"]');
                                $item.find('.scheduletime').text(scheduleTime);
                                $item.find('.observationlocation').text(page.scheduleExamRequest.ResourceLocation || "");
              
                                if (((page.scheduleExamRequest.ScheduleNotice || '').length > 7)) {
                                    var scheduleNoticeStr = page.scheduleExamRequest.ScheduleNotice.substring(0, 7) + '...';
                                    $item.find('.scheduleNotice').text(scheduleNoticeStr || "");
                                } else {
                                    $item.find('.scheduleNotice').text(page.scheduleExamRequest.ScheduleNotice || "");
                                }
                                
                                return false;
                            }
                        });
                    }
                    $('.ampm_comtainer_sub').html('');
                    $('#main_container').show();
                    $('#time_container').hide();

                    var startDate = imcis.convertDateFromJson(page.scheduleExamRequest.ScheduleStartDate);
                    var endDate = imcis.convertDateFromJson(page.scheduleExamRequest.ScheduleEndDate);
                    var startTimeDetail = imcis.convertDateFromJson(page.scheduleExamRequest.ScheduleStartTimeDetail);
                    var endTimeDetail = imcis.convertDateFromJson(page.scheduleExamRequest.ScheduleEndTimeDetail);
                    var scheduleTime = startDate.substr(0, 16) + "-" + endDate.substr(11, 5);
                    var showTimeType = schedule.GetSysParameterValueByExamRequest(page.scheduleExamRequest, mobileScheduleShowTimeType);
                    switch (showTimeType) {
                        case '1':
                            if (n && n.ScheduleStartTimeDetail) {
                                scheduleTime = startTimeDetail.substr(0, 16) + "-" + endTimeDetail.substr(11, 5);
                            }
                            break;
                        case '2':
                            scheduleTime = startDate;
                            break;
                        case '3':
                            if (n && n.ScheduleStartTimeDetail) {
                                scheduleTime = startTimeDetail;
                            } else {
                                scheduleTime = startDate;
                            }
                            break;
                        case '4':   //签到时间范围 开始时间  allowRegistByScheduleDateAhead  结束时间  allowRegistByScheduleDateLate
                            scheduleTimeTitle = "签到时间";
                            var startDate4 = page.getDateByParameters(n, startDate, allowRegistByScheduleDateAhead);
                            var endDate4 = page.getDateByParameters(n, endDate, allowRegistByScheduleDateLate);
                            scheduleTime = startDate4.substr(0, 16) + "-" + endDate4.substr(11, 5);
                            break;
                        case '5':   //签到开始时间
                            scheduleTimeTitle = "签到时间";
                            scheduleTime = page.getDateByParameters(n, startDate, allowRegistByScheduleDateAhead);
                    }

                    $('.ifbook_items[data-placerorderno="' + placerOrderNO + '"]').find('.scheduletime').text(scheduleTime);
                    $('.ifbook_items[data-placerorderno="' + placerOrderNO + '"]').attr('data-ObservationUID', page.scheduleExamRequest.ObservationUID);
                    $('.ifbook_items[data-PlacerOrderNO="' + placerOrderNO + '"]').find('.observationlocation').text(page.scheduleExamRequest.ResourceLocation || "");

                    if (((page.scheduleExamRequest.ScheduleNotice || '').length > 7)) {
                        var scheduleNoticeStr = page.scheduleExamRequest.ScheduleNotice.substring(0, 7) + '...';
                        $('.ifbook_items[data-PlacerOrderNO="' + placerOrderNO + '"]').find('.scheduleNotice').text(scheduleNoticeStr || "");
                    } else {
                        $('.ifbook_items[data-PlacerOrderNO="' + placerOrderNO + '"]').find('.scheduleNotice').text(page.scheduleExamRequest.ScheduleNotice || "");
                    }
                    
                    $('body').css({ 'background': '#f2f2f2' });

                    pageEvent.returnUrlTipsAfterSave();
                }
            }, function () {
                page.saveExamScheduleFlag = false;
                page.isScheduleTimeSelectPage = false;
            });
        },

        //一键预约多个检查申请
        saveMultiExamSchedule: function () {
            if (page.unFinishList.length == 0) {
                schedule.alert('您没有待预约记录！');
                return false;
            }

            var list = [];
            for (var i = 0; i < page.unFinishList.length; i++) {
                if (page.unFinishList[i].NeedScheduleFlag) {
                    if (page.unFinishList[i].orderList && page.unFinishList[i].orderList.length > 0) {
                        for (var j = 0; j < page.unFinishList[i].orderList.length; j++) {
                            page.unFinishList[i].orderList[j].ScheduleRoute = scheduleRoute || 5;
                            list.push(page.unFinishList[i].orderList[j]);
                        }
                    } else {
                        page.unFinishList[i].ScheduleRoute = scheduleRoute || 5;
                        list.push(page.unFinishList[i]);
                    }
                }
            }

            if (list.length == 0) {
                schedule.alert('目前您没有可以自助预约的检查申请!');
            }

            if (list.length > 0) {
                imcis.ajax(schedule.relativeUrl + 'SaveExamScheduleAuto', list, true, function (data) {
                    if (data && data.success) {
                        for (var i = 0; i < data.resultList.length; i++) {
                            $.each(page.unFinishList, function (j, n) {
                                if (data.resultList[i].PlacerOrderNO == n.PlacerOrderNO) {
                                    var exam = n;
                                    exam.ScheduleSeq = data.resultList[i].ScheduleSeq;
                                    exam.ScheduleID = data.resultList[i].ScheduleID;
                                    exam.ScheduleResourceUID = data.resultList[i].ScheduleResourceUID;
                                    exam.ScheduleResourceName = data.resultList[i].ScheduleResourceName;
                                    exam.ScheduleStartDate = data.resultList[i].ScheduleStartDate;
                                    exam.ScheduleEndDate = data.resultList[i].ScheduleEndDate;
                                    exam.ScheduleTimeDetail = data.resultList[i].ScheduleTimeDetail;
                                    exam.ScheduleStartTimeDetail = data.resultList[i].ScheduleStartTimeDetail;
                                    exam.ScheduleEndTimeDetail = data.resultList[i].ScheduleEndTimeDetail;
                                    exam.ScheduleNotice = data.resultList[i].ScheduleNotice;
                                    exam.ResourceLocation = data.resultList[i].ResourceLocation;
                                    exam.ScheduleFlag = true;
                                    exam.ScheduleStatus = 0;
                                    page.finishList.push(exam);
                                    $('.unbook_itemslist[data-PlacerOrderNO="' + exam.PlacerOrderNO + '"]').remove();
                                    page.bindFinish(exam);
                                    page.unFinishList.splice(j, 1);
                                    return false;
                                } else if (n.PlacerOrderNO.indexOf(data.resultList[i].PlacerOrderNO) > -1) {
                                    var exam = n;
                                    exam.ScheduleSeq = data.resultList[i].ScheduleSeq;
                                    exam.ScheduleID = data.resultList[i].ScheduleID;
                                    exam.ScheduleResourceUID = data.resultList[i].ScheduleResourceUID;
                                    exam.ScheduleResourceName = data.resultList[i].ScheduleResourceName;
                                    exam.ScheduleStartDate = data.resultList[i].ScheduleStartDate;
                                    exam.ScheduleEndDate = data.resultList[i].ScheduleEndDate;
                                    exam.ScheduleTimeDetail = data.resultList[i].ScheduleTimeDetail;
                                    exam.ScheduleStartTimeDetail = data.resultList[i].ScheduleStartTimeDetail;
                                    exam.ScheduleEndTimeDetail = data.resultList[i].ScheduleEndTimeDetail;
                                    exam.ScheduleNotice = data.resultList[i].ScheduleNotice;
                                    exam.ResourceLocation = data.resultList[i].ResourceLocation;
                                    exam.ScheduleFlag = true;
                                    exam.ScheduleStatus = 0;
                                    for (var k = 0; k < n.orderList.length; k++) {
                                        var examsub = n.orderList[k];
                                        examsub.ScheduleSeq = data.resultList[i].ScheduleSeq;
                                        examsub.ScheduleID = data.resultList[i].ScheduleID;
                                        examsub.ScheduleResourceUID = data.resultList[i].ScheduleResourceUID;
                                        examsub.ScheduleResourceName = data.resultList[i].ScheduleResourceName;
                                        examsub.ScheduleStartDate = data.resultList[i].ScheduleStartDate;
                                        examsub.ScheduleEndDate = data.resultList[i].ScheduleEndDate;
                                        examsub.ScheduleTimeDetail = data.resultList[i].ScheduleTimeDetail;
                                        examsub.ScheduleStartTimeDetail = data.resultList[i].ScheduleStartTimeDetail;
                                        examsub.ScheduleEndTimeDetail = data.resultList[i].ScheduleEndTimeDetail;
                                        examsub.ScheduleNotice = data.resultList[i].ScheduleNotice;
                                        examsub.ResourceLocation = data.resultList[i].ResourceLocation;
                                        examsub.ScheduleFlag = true;
                                        examsub.ScheduleStatus = 0;
                                    }

                                    page.finishList.push(exam);
                                    $('.unbook_itemslist[data-PlacerOrderNO="' + exam.PlacerOrderNO + '"]').remove();
                                    page.bindFinish(exam);
                                    page.unFinishList.splice(j, 1);
                                    return false;
                                }
                            });
                        }
                        page.updateStatus();
                        pageEvent.returnUrlTipsAfterSave();
                    } else {
                        schedule.alert(data.errorMsg || '一键预约失败，请重试');
                    }
                });
            }
        },
        //获取单个申请的预约资源排班请求错误处理
        getScheduleInfoErrCallback: function () {
            $('.time_section').hide();
            $('.ampm_comtainer_sub').remove();
            $('#time_container').append('<div class="ampm_comtainer_sub">没有可预约的时间，请切换日期。</div>');
        },
        //获取单个申请的预约资源排班
        getScheduleInfoCallback: function (data, getRemainNumberFlag) {
            if(data.ResourceUID && data.ScheduleDate && data.ScheduleTime) {
                page.scheduleExamRequest.ScheduleResourceUID = data.ResourceUID;
                page.scheduleExamRequest.ScheduleResourceName = data.ResourceName;
                page.scheduleExamRequest.ScheduleStartDate = data.ScheduleDate + " " + data.ScheduleTime.split('-')[0];
                page.scheduleExamRequest.ScheduleEndDate = data.ScheduleDate + " " + data.ScheduleTime.split('-')[1];
                page.scheduleExamRequest.Quantity = data.Quantity;
                page.scheduleExamRequest.ScheduleFlag = data.ScheduleFlag;
                page.scheduleExamRequest.OccupyNumber = data.OccupyNumber;
            }
            //初始化时间选择界面
            if (schedule.startDate) {
                $('#time_container .ampm_comtainer').html('');
                $('#main_container').hide();
                $('#time_container').show();
                $('body').css({ 'background': '#fff' });
                $('#save_time').hide();
            }

            if (data.ScheduleArrangeResourceInfoList.length == 0) {
                $('.select_days').hide();
                $('.ampm_comtainer_sub').remove();
                $('#time_container').append('<div class="ampm_comtainer_sub">没有可预约的时间，请切换日期。</div>');
                return;
            }
            var resource = data.ScheduleArrangeResourceInfoList[0];
            $('#time_container').attr('data-resourceuid', resource.ResourceUID)
                                .attr('data-resourcename', resource.ResourceName)
                                .attr('data-resourcelocation', resource.ResourceLocation);

            if (resource.ScheduleArrangeDateInfoList.length == 0) {
                $('.time_section').hide();
                $('.ampm_comtainer_sub').remove();
                $('#time_container').append('<div class="ampm_comtainer_sub">没有可预约的时间，请切换日期。</div>');
                return;
            }

            $('#time_container .ampm_comtainer_sub').show();
            var arrangeDateInfo = resource.ScheduleArrangeDateInfoList[0];

            //节假日设置了不可预约
            if (arrangeDateInfo.IsHolidayDisable && !arrangeDateInfo.RuleArrangeActiveFlag) {
                $('.time_section').hide();
                $('.ampm_comtainer_sub').remove();
                $('#time_container').append('<div class="ampm_comtainer_sub">没有可预约的时间，请切换日期。</div>');
                return;
            }

            var arrangeDay = imcis.convertDateFromJson(arrangeDateInfo.ArrangeDay, true);
            if (page.isScheduleTimeSelectPage) {
                if (arrangeDay > schedule.startDate) {
                    $('.time_section').hide();
                    $('.ampm_comtainer_sub').remove();
                    $('#time_container').append('<div class="ampm_comtainer_sub">没有可预约的时间，请切换日期。</div>');
                    $('#changeTime').val(schedule.startDate);
                    return;
                }
               
            }

            var showTimeType = schedule.GetSysParameterValueByExamRequest(data, mobileScheduleShowTimeType);
            var showRemainNumber = schedule.GetSysParameterValueByExamRequest(data, mobileScheduleShowRemainNumber);      
            pageEvent.addSelectDays(showRemainNumber, arrangeDateInfo, showTimeType); 
            $('#changeTime').val(arrangeDay);

            if (showRemainNumber == "1") {
                if (getRemainNumberFlag) {
                    pageEvent.timeShowRemainNumber();
                } else {
                    pageEvent.addRemainNumberDiv(page.arrangeDayList);
                }
            }
        },

        //时间组添加时间段
        addGroupTime: function (groupName, showRemainNumber, scheduleArrange, showTimeType) {
            var hasAllowScheduleTime = false;
            var times = scheduleArrange;
            var temp = '<div class="ampm_comtainer_sub" data-groupname="' + groupName + '">';
            var time_section = '';//选中上下午
            for (var i = 0; i < times.length; i++) {
                var scheduleTime = times[i].StartTime + "-" + times[i].EndTime;
                var time = scheduleTime;

                switch(showTimeType){
                    case '2':
                    case '3':
                        time = times[i].StartTime;
                        break;
                    default:
                        break;
                }

                if (time_section == '' && groupName == 'morning') {
                    time_section = 'morning';
                } else if (time_section == '' && groupName == 'afternoon') {
                    time_section == 'afternoon'
                } else if (time_section == '' && !times[i].AfternoonFlag) {
                    time_section = 'morning';
                } else if (time_section == '' && times[i].AfternoonFlag) {
                    time_section = 'afternoon';
                }

                if (time_section == 'morning' && times[i].StartTime >= '12:00') {
                    continue;
                } else if (groupName == 'afternoon' && times[i].StartTime < '12:00') {
                    continue;
                }
                var pollHtml = showRemainNumber == "1" ? '<br/><span style="font-size:10px;">&nbsp;剩余' + (times[i].Quantity - times[i].AppointmentQuantity) + '</span>' : "";
                var lHeight = showRemainNumber == "1" ? "l-height" : "";
                switch (times[i].ScheduleTimeStatus) {
                    case 3:
                    case 4:
                        //不可预约时间
                        temp += '<div  class="pull-left width_continer "  ><div class="ampm_chosing pull-left schedule-disable ' + lHeight + '" data-chose="cant"   data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" data-resourceuid="' +( times[i].ResourceUID || '') + '" data-resourcename="'+( times[i].ResourceName || '')+'" data-resourcelocation="'+( times[i].ResourceLoaction || '')+'"  ><span class="scheduleTime" data-time="'+scheduleTime+'">' + time + '</span>' + pollHtml + '</div></div>';
                        break;
                    case 0:
                        //选中的时间
                        temp += '<div  class="pull-left width_continer "  ><div  class="ampm_chosing pull-left schedule-current  ' + lHeight + '" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" data-resourceuid="' +( times[i].ResourceUID || '') + '" data-resourcename="'+( times[i].ResourceName || '')+'" data-resourcelocation="'+( times[i].ResourceLoaction || '')+'" ><span class="scheduleTime" data-time="'+scheduleTime+'">' + time + '</span>' + pollHtml + '</div></div>';
                        hasAllowScheduleTime = true;
                        break;
                    case 1:
                        //已预约时间
                        temp += '<div  class="pull-left width_continer "  ><div  class="ampm_chosing pull-left  schedule-finish  ' + lHeight + '" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" data-resourceuid="' +( times[i].ResourceUID || '') + '" data-resourcename="'+( times[i].ResourceName || '')+'" data-resourcelocation="'+( times[i].ResourceLoaction || '')+'" ><span class="scheduleTime" data-time="'+scheduleTime+'">' + time + '</span>' + pollHtml + '</div></div>';
                        hasAllowScheduleTime = true;
                        break;
                    default:
                        //可预约时间
                        temp += '<div class="pull-left width_continer " > <div  class="ampm_chosing pull-left schedule-enable  ' + lHeight + '" data-uid="' + times[i].TimeDetailUID + '" data-quantity="' + times[i].Quantity + '" data-resourceuid="' +( times[i].ResourceUID || '') + '" data-resourcename="'+( times[i].ResourceName || '')+'" data-resourcelocation="'+( times[i].ResourceLoaction || '')+'"><span class="scheduleTime" data-time="'+scheduleTime+'">' + time + '</span>' + pollHtml + '</div></div>';
                        hasAllowScheduleTime = true;
                        break;
                }
            }

            temp += '</div>';
            $('#save_time').show();
            $('.ampm_comtainer_sub').remove();
            $('#time_container').append(temp);
            $('.ampm_comtainer_sub').height($(window).height() - 204);
            $('.ampm_comtainer_sub').css({'margin-top':$('#time_isbook').height()+20 });

            $('.morning,.afternoon').removeClass('active').removeClass('unactive');
            if (time_section == 'morning') {
                $('.time_section .morning').addClass('active');
                $('.time_section .afternoon').addClass('unactive');
            } else {
                $('.time_section .afternoon').addClass('active');
                $('.time_section .morning').addClass('unactive');
            }

            if (!hasAllowScheduleTime) {
                $('.ampm_comtainer_sub').remove();
                $('.ampm_comtainer_sub').height($(window).height() - 204);
                $('.ampm_comtainer_sub').css({ 'margin-top': $('#time_isbook').height() + 20 });
                $('#time_container').append('<div class="ampm_comtainer_sub">没有可预约的排班时间！</div>');
            }
        },
        //选中时间
        selectTime: function () {
            var $this = $(this);
            if ($this.hasClass('schedule-disable')) {
                return;
            } else if ($this.hasClass('schedule-enable')) {
                $('#time_container .schedule-current').removeClass('schedule-current').addClass('schedule-enable');
                $this.removeClass('schedule-enable').addClass('schedule-current');
            } else if ($this.hasClass('schedule-finish')) {
                $('#time_container .schedule-current').removeClass('schedule-current').addClass('schedule-enable');
            }

            var $source = $('#time_container');
            page.scheduleExamRequest.ScheduleResourceUID = $this.attr('data-resourceuid') ||  $source.attr('data-resourceuid');
            page.scheduleExamRequest.ScheduleResourceName =$this.attr('data-resourcename') ||  $source.attr('data-resourcename');
            page.scheduleExamRequest.ResourceLocation = $this.attr('data-resourcelocation') || $source.attr('data-resourcelocation');

            //var scheduleTime = $(this).text();
            var scheduleTime = $this.find(".scheduleTime").data('time');
            var scheduleDate = $('#changeTime').val();

            page.scheduleExamRequest.ScheduleStartDate = scheduleDate + " " + scheduleTime.split('-')[0];
            page.scheduleExamRequest.ScheduleEndDate = scheduleDate + " " + scheduleTime.split('-')[1];
            page.scheduleExamRequest.Quantity = $this.data('quantity');

            if (page.scheduleExamRequest.ScheduleResourceName == page.scheduleExamRequest.OriginalScheduleResourceName &&
                        page.scheduleExamRequest.ScheduleStartDate == page.scheduleExamRequest.OriginalScheduleStartDate &&
                        page.scheduleExamRequest.ScheduleEndDate == page.scheduleExamRequest.OriginalScheduleEndDate) {
                page.scheduleExamRequest.ChangeFlag = false;
                page.scheduleExamRequest.ScheduleFlag = false;
            } else {
                page.scheduleExamRequest.ChangeFlag = true;
                page.scheduleExamRequest.ScheduleFlag = true;
            }
        },
        //手机是否显示签到界面
        judgingMobileScheduleCheckinInterface: function (examRequestList) {
            if (examRequestList.length != 0) {
                for (var i = 0; i < examRequestList.length; i++) {
                    examRequestList[i].MobileCheckin = schedule.GetSysParameterValueByExamRequest(examRequestList[i], MobileScheduleCheckin) == "1" ? true : false;
                    if (examRequestList[i].MobileCheckin) {
                        page.showMobileScheduleCheckinInterface = examRequestList[i].MobileCheckin;
                        break;
                    }
                }
            } else {
                page.showMobileScheduleCheckinInterface = schedule.GetSysParameterValueByExamRequest("", MobileScheduleCheckin) == "1" ? true : false;
            }
            
            if (!page.showMobileScheduleCheckinInterface) {//不签到，修改整体界面
                $('#sign').css("display", "none");
                $('#unbook_title').css("width", "42.5%");
                $("#book_title").css("width", "42.5%");
            } else {
                //签到，整体界面保持原样
            }                       
        },
        //检查项目是否支持手机签到
        judgingExamRequestMatchCheckin: function (examRequest) {
            if (examRequest.MobileCheckin == false || examRequest.MobileCheckin == true)//获取申请单时，已经对检查项目进行过判断
            {
                return examRequest.MobileCheckin;
            } else {//之前未对检查项目是否支持手机签到判断
                return schedule.GetSysParameterValueByExamRequest(examRequest, MobileScheduleCheckin) == "1" ? true : false;
            }
        },
        //申请单自助预约已预约列表显示检查状态。
        judgingExamRequestMatchResultStatus: function (examRequest) {
            if (pageEvent.judgingExamRequestMatchCheckin(examRequest)) {    //是否开启手机签到功能
                return true;
            } 
            //不开启手机签到功能该参数才起效
            var selfScheduleListResultStatusOfExamRequest = schedule.GetSysParameterValueByExamRequest(examRequest, scheduleSelfScheduleListResultStatus);
            if (selfScheduleListResultStatusOfExamRequest == "") {
                return ["预约完成", "登记完成"].indexOf(examRequest.ResultStatus) > -1 ? true : false;
            } else {
                return selfScheduleListResultStatusOfExamRequest.split(",").indexOf(examRequest.ResultStatus) > -1 ? true : false;
            }
        },
        //弹出申请单
        alertExamRequest: function (order,$this) {
            $('#examRequest_title').text('回执单');

            //预约结果打开
            if ($this.parents('#examRequestResult_container').length > 0) {
                $('#examRequest_container').attr({ 'data-whoOpen': 'examRequestResult_container' });
                $('#examRequestResult_container').hide();
            } else {
                //接口进入预约详情页面，ReturnUrl为空预约回执单界面不显示返回按钮。
                //if (detailView == '1' && !returnUrl) {
                //    $('#examRequest_back').off();
                //    $('#examRequest_back').parent().css({ 'display': 'none' });
                //}

                if ($this.parents('#main_container').length > 0) {
                    //列表打开
                    $('#examRequest_container').attr({ 'data-whoOpen': 'main_container' });
                    $('#time_container').hide();
                    $('#main_container').hide();
                } else if ($this.parents('#time_container').length > 0) {
                    //预约详情打开
                    $('#examRequest_container').attr({ 'data-whoOpen': 'time_container' });
                    $('#time_container').hide();
                    $('#main_container').hide();
                } else {
                    $('#time_container').hide();
                    $('#main_container').hide();
                }
            } 

            imcis.ajax(schedule.relativeUrl + 'GetPrintExamScheduleReceipt', {observationUID: order.ObservationUID }, true, function (ret) {
                if (ret) {
                    if (ret.image) {
                        $('#examRequest_main img').css({ 'display': '' }).attr({ 'src': ret.image });
                        $('#examRequest_main, #examRequest_container').css({ 'display': '', 'left': '0px', 'top': '50px', 'z-index': '10' });
                        $('#examRequest_main .examRequest_remind').css({ 'display': 'none' });
                    } else if (ret.errorMsg) {
                        $('#examRequest_main img').css({ 'display': 'none' });
                        $('#examRequest_main .examRequest_remind').css({ 'display': '' }).text(ret.errorMsg);
                    }
                    $('#time_container').hide();
                    $('#main_container').hide();
                    $('#examRequestResult_container').hide();
                }
            });
        },
        //显示不提供自助预约原因
        showNotScheduleMemo:function($this,list) {
            var placerOrderNO = $this.closest('.ifbook_items').data("placerorderno");
            $.each(list, function (i, n) {
                if (placerOrderNO == n.PlacerOrderNO) {
                    if (n.ScheduleStatus+'' === '0' && n.OperationMemo && n.OperationMemo.length > 12) {
                        schedule.alert(n.OperationMemo);
                        return false;
                    } else if(n.OperationMemo && n.OperationMemo.length > 15){
                        schedule.alert(n.OperationMemo);
                        return false;
                    } else if(n.OperationMemo == '未缴费不允许预约。') {
                        schedule.alert(n.OperationMemo);
                        return false;
                    }
                }
            });
        },
        //加载日期剩余数量
        addRemainNumberDiv: function (arrangeDayList) {
            for (var key in arrangeDayList) {
                var $div = $("#time_container>#time_isbook>.days>div[data-arrangeday='" + key + "']");
                if ($div.find(".remainNumber").length > 0) {
                    $div.find(".remainNumber").remove();
                }
                if ($div.find(".pregnantWeek").length > 0) {
                    continue;
                }
                $div.append('<div class="remainNumber">剩余' + arrangeDayList[key] + '</div>');
            }
        },
        timeShowRemainNumber: function () {
            var data = page.scheduleExamRequest;
            data.ResourceUID = "";
            data.Days = 1;
            data.DoctorName = "";
            data.ExamRequestScheduleArrageInfoList = [];
            data.IgnoreScheduleFlag = true;
            var count = 0, len = Object.keys(page.arrangeDayList).length;
            for (var key in page.arrangeDayList) {
                data.StartDate = key;
                imcis.ajax(schedule.relativeUrl + "GetScheduleInfo", data, true, function (ret) {
                    count++;
                    if (ret) {
                        if (ret.success) {
                            var arrangeDateInfo = ret.result.ScheduleArrangeResourceInfoList[0].ScheduleArrangeDateInfoList[0];
                            var arrangeDay = imcis.convertDateFromJson(arrangeDateInfo.ArrangeDay, true);

                            var pmRemainNumber = 0, amRemainNumber = 0;
                            var timeList = arrangeDateInfo.ScheduleArrangeTimeInfoList;
                            for (var i = 0; i < timeList.length; i++) {
                                if (timeList[i].StartTime < '12:00') { //上午
                                    amRemainNumber += timeList[i].Quantity - timeList[i].AppointmentQuantity;
                                } else if (timeList[i].StartTime >= '12:00') { //下午
                                    pmRemainNumber += timeList[i].Quantity - timeList[i].AppointmentQuantity;
                                }
                            }
                            //console.log("page.arrangeDayList[" + arrangeDay + "] = " + (pmRemainNumber + amRemainNumber) + ";pmRemainNumber=" + pmRemainNumber + ";amRemainNumber=" + amRemainNumber);
                            page.arrangeDayList[arrangeDay] = pmRemainNumber + amRemainNumber;
                            if (count == len) {
                                pageEvent.addRemainNumberDiv(page.arrangeDayList);
                            }
                        } 
                    }
                });
            }
        },
        //加载日期
        addSelectDays: function (showRemainNumber, arrangeDateInfo, showTimeType) {
            function getChineseWeek(week) {
                switch (week) {
                    case 1:
                        return '周一';
                    case 2:
                        return '周二';
                    case 3:
                        return '周三';
                    case 4:
                        return '周四';
                    case 5:
                        return '周五';
                    case 6:
                        return '周六';
                    case 7:
                        return '周日';
                }
            }
            $('.pregnantWeek').remove();
            var arrangeDay = imcis.convertDateFromJson(arrangeDateInfo.ArrangeDay, true);
            var timeList = arrangeDateInfo.ScheduleArrangeTimeInfoList;
            if (timeList.length == 0) {
                $('.select_days').hide();
                $('.ampm_comtainer_sub').remove();
                $('#time_container').append('<div class="ampm_comtainer_sub">' + arrangeDay + ',没有可预约的排班时间!</div>');
                return;
            }
            var amRemainNumber = 0; //arrangeDateInfo.AMQuantity - arrangeDateInfo.AMAppointmentQuantity;
            var pmRemainNumber = 0; //arrangeDateInfo.PMQuantity - arrangeDateInfo.PMAppointmentQuantity;

            for (var i = 0; i < timeList.length; i++) {
                if (timeList[i].StartTime < '12:00') {
                    amRemainNumber += timeList[i].Quantity - timeList[i].AppointmentQuantity;
                } else if (timeList[i].StartTime >= '12:00') {
                    pmRemainNumber += timeList[i].Quantity - timeList[i].AppointmentQuantity;
                } 
            }

            if (!page.isScheduleTimeSelectPage) {
                $('.day,.selected_day,.time_section').remove();

                //绑定界面上的日期
                var selectDateHtml = '';
                var oneDay = 1000 * 60 * 60 * 24;
                var arrangeDay0 = arrangeDay.substr(arrangeDay.indexOf('-') + 1);
                var arrangeWeek = getChineseWeek(arrangeDateInfo.ArrangeWeek);
                selectDateHtml += '<div class="selected_day" data-arrangeDay="' + arrangeDay + '"><div>' + arrangeDay0 + '</div><div>' + arrangeWeek + '</div></div>';

                var mPollHtml = "", aPollHtml = "";
                if (showRemainNumber == "1") {
                    page.arrangeDayList = {};
                    mPollHtml = '<span style="font-size:12px;">&nbsp;剩余' + amRemainNumber + '</span>';
                    aPollHtml = '<span style="font-size:12px;">&nbsp;剩余' + pmRemainNumber + '</span>';
                    page.arrangeDayList[arrangeDay] = amRemainNumber + pmRemainNumber;
                }
                //显示推荐日期之后五天的日期
                autoIncremenetDateFromArrangeDay = new Date(arrangeDay);
                for (var i = 0; i < 5; i++) {
                    autoIncremenetDateFromArrangeDay = new Date(autoIncremenetDateFromArrangeDay.getTime() + oneDay);
                    var arrangeWeekAfter = getChineseWeek(autoIncremenetDateFromArrangeDay.getDay() == 0 ? 7 : autoIncremenetDateFromArrangeDay.getDay());
                    var autoIncremenetDateString = imcis.date.dateStringFromDate(autoIncremenetDateFromArrangeDay);
                    var arrangeDayAfter = autoIncremenetDateString.substr(autoIncremenetDateString.indexOf('-') + 1);
                    selectDateHtml += '<div class="day" data-arrangeDay="' + autoIncremenetDateString + '"><div>' + arrangeDayAfter + '</div><div>' + arrangeWeekAfter + '</div></div>';
                    page.arrangeDayList[autoIncremenetDateString] = 0;
                }
                $('.select_days .days').prepend(selectDateHtml);
                $('#time_isbook').append('<div class="time_section"><div class="morning">上午' + mPollHtml + '</div><div class="afternoon">下午' + aPollHtml + '</div></div>'); 
            } else {
                $("#time_isbook>.time_section>.morning>span").text(' 剩余' + amRemainNumber);
                $("#time_isbook>.time_section>.afternoon>span").text(' 剩余' + pmRemainNumber);
            }
            $('.time_section').show();

            if(arrangeDateInfo.PregnantWeek) {
                $('.selected_day').append('<div class="pregnantWeek">' + arrangeDateInfo.PregnantWeek + '</div>');
            }

            pageEvent.addGroupTime('全天', showRemainNumber, timeList, showTimeType);

            $('.selected_day,.day').unbind('click');
            $('.morning,.afternoon').unbind('click');
            //绑定日期点击事件
            $('.selected_day,.day').on('click', function () {
                var $this = $(this);
                var arrangeDay = $this.attr('data-arrangeDay');
                if ($this.hasClass('selected_day')) {
                    return;
                }

                page.isScheduleTimeSelectPage = true;
                $('.days div.selected_day').removeClass('selected_day').addClass('day');
                $this.addClass('selected_day').removeClass('day');

                schedule.startDate = arrangeDay;
                schedule.days = 1;
                schedule.IgnoreScheduleFlag = true;
                schedule.getScheduleInfo(page.scheduleExamRequest, [], "", "", null, pageEvent.getScheduleInfoCallback, pageEvent.getScheduleInfoErrCallback);
            })

            //绑定上下午点击事件
            $('.morning,.afternoon').on('click', function () {
                var $this = $(this);
                if ($('.selected_day').length == 0) {
                    schedule.alert(arrangeDay + '请先选择一个日期！');
                    return;
                }

                var selectDay = $('.selected_day').attr('data-arrangeDay');
                if (timeList.length == 0) {
                    $('.ampm_comtainer_sub').remove();
                    $('#time_container').append('<div class="ampm_comtainer_sub">' + selectDay + '，没有可预约的排班时间！</div>');
                    return;
                }

                if ($this.hasClass('morning')) {
                    pageEvent.addGroupTime('morning', showRemainNumber, timeList, showTimeType);
                } else {
                    pageEvent.addGroupTime('afternoon', showRemainNumber, timeList, showTimeType);
                }
            })
        },
        //时间字符串输出完整格式如：2021-1-1 -> 2021-01-01
        dateFullformat: function (dataStr, type) {
            var arr = dataStr.split(" ");
            var y = arr[0].split("-");
            for (var i = 0; i < y.length; i++) {
                var item = parseInt(y[i]);
                if (item < 10)
                    y[i] = "0" + item;
            }
            var date = y[0] + "-" + y[1] + "-" + y[2];
            if (type == "yyyy-MM-dd")
                return date;
            return date + " " + arr[1];
        },
        //点击时间下拉框中的具体时间，为时间控件赋值
        getQueryDateMenuItemClick: function (id) {
            var n, date, endDate; //n星期几减1，date开始时间日期，endDate结束时间日期
            var now = new Date(),
                startTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " 00:00:00",
                endTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " 23:59:59",
                oneDay = 1000 * 60 * 60 * 24,
                oneHour = 1000 * 60 * 60;
            var idArray = id.split('|');
            if (idArray.length == 2) {
                var idStartTime = '', idEndTime = '';
                if (idArray[0].indexOf('-') > -1) {
                    idArray0 = idArray[0].split('-');
                } else if (idArray[0].indexOf('+') > -1) {
                    idArray0 = idArray[0].split('+');
                }
                if (idArray[1].indexOf('-') > -1) {
                    idArray1 = idArray[1].split('-');
                } else if (idArray[1].indexOf('+') > -1) {
                    idArray1 = idArray[1].split('+');
                }
                //开始时间
                switch (idArray0[0]) {
                    case "Hour":
                        if (idArray[0].indexOf('-') > -1) {
                            date = new Date(now.getTime() - idArray0[1] * oneHour);
                        } else if (idArray[0].indexOf('+') > -1) {
                            date = new Date(now.getTime() + idArray0[1] * oneHour);
                        }
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":00:00";
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        break;
                    case "Today":
                        if (idArray[0].indexOf('-') > -1) {
                            date = new Date(now.getTime() - idArray0[1] * oneDay);
                        } else if (idArray[0].indexOf('+') > -1) {
                            date = new Date(now.getTime() + idArray0[1] * oneDay);
                        }
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        break;
                    case "Week":
                        if (idArray[0].indexOf("+") > -1) {
                            date = new Date(now.getTime() + (7 * 24 * 3600 * 1000) * idArray0[1]);
                            var week = date.getDay() == 0 ? 7 : date.getDay();
                            date = new Date(date.getTime() - oneDay * (week - 1));
                            startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                        } else if (idArray[0].indexOf("-") > -1) {
                            date = new Date(now.getTime() - (7 * 24 * 3600 * 1000) * idArray0[1]);
                            var week = date.getDay() == 0 ? 7 : date.getDay();
                            date = new Date(date.getTime() - oneDay * (week - 1));
                            startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                        }
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        break;
                    case "Month":
                        date = new Date(now);
                        if (idArray[0].indexOf('-') > -1) {
                            date.setMonth(parseInt(date.getMonth()) - idArray0[1]);
                        } else if (idArray[0].indexOf('+') > -1) {
                            date.setMonth(parseInt(date.getMonth()) + parseInt(idArray0[1]));
                        }
                        startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-01 00:00:00";
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        break;
                    case "Year":
                        date = new Date(now);
                        if (idArray[0].indexOf('-') > -1) {
                            date.setYear(parseInt(date.getFullYear()) - parseInt(idArray0[1]));
                        } else if (idArray[0].indexOf('+') > -1) {
                            date.setYear(parseInt(date.getFullYear()) + parseInt(idArray0[1]));
                        }
                        startTime = date.getFullYear() + "-01-01 00:00:00";
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        break;
                    default:
                        break;
                }

                //结束时间
                switch (idArray1[0]) {
                    case "Hour":
                        if (idArray[1].indexOf('-') > -1) {
                            date = new Date(now.getTime() - idArray1[1] * oneHour);
                        } else if (idArray[1].indexOf('+') > -1) {
                            date = new Date(now.getTime() + idArray1[1] * oneHour);
                        }
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":59:59";
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Today":
                        if (idArray[1].indexOf('-') > -1) {
                            date = new Date(now.getTime() - idArray1[1] * oneDay);
                        } else if (idArray[1].indexOf('+') > -1) {
                            date = new Date(now.getTime() + idArray1[1] * oneDay);
                        }
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Week":
                        if (idArray[1].indexOf("+") > -1) {
                            date = new Date(now.getTime() + (7 * 24 * 3600 * 1000) * idArray1[1]);
                            var week = date.getDay() == 0 ? 7 : date.getDay();
                            date = new Date(date.getTime() + oneDay * (7 - week));
                            endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                        } else if (idArray[1].indexOf("-") > -1) {
                            date = new Date(now.getTime() - (7 * 24 * 3600 * 1000) * idArray1[1]);
                            var week = date.getDay() == 0 ? 7 : date.getDay();
                            date = new Date(date.getTime() + oneDay * (7 - week));
                            endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                        }
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Month":
                        date = new Date(now);
                        if (idArray[1].indexOf('-') > -1) {
                            date.setMonth(parseInt(date.getMonth()) - idArray1[1]);
                        } else if (idArray[1].indexOf('+') > -1) {
                            date.setMonth(parseInt(date.getMonth()) + parseInt(idArray1[1]));
                        }
                        var month = date.getMonth();
                        date = new Date(new Date(date.getFullYear(), ++month, 1) - oneDay);
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Year":
                        date = new Date(now);
                        if (idArray[1].indexOf('-') > -1) {
                            date.setYear(parseInt(date.getFullYear()) - parseInt(idArray1[1]));
                        } else if (idArray[1].indexOf('+') > -1) {
                            date.setYear(parseInt(date.getFullYear()) + parseInt(idArray1[1]));
                        }
                        var currentYear = date.getFullYear();
                        date = new Date(new Date(++currentYear, 0, 1) - oneDay);//结束年份的最后一天
                        endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    default:
                        break;
                }
            } else {
                var itemSplit = id.split('-');
                if (itemSplit.length < 2) {
                    itemSplit = id.split('+');
                }
                switch (itemSplit[0]) {
                    case "All":
                        $("#txt-datetimestart").val("");
                        $("#txt-datetimeend").val("");
                        break;
                    case "Custom":
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Hour":
                        if (id.indexOf("+") > -1) {
                            date = new Date(now.getTime() + itemSplit[1] * oneHour);
                            endTime = startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                            startTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
                        } else if (id.indexOf("-") > -1) {
                            date = new Date(now.getTime() - itemSplit[1] * oneHour);
                            startTime = startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                            endTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
                        }

                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Today":
                        if (id.indexOf("+") > -1) {
                            date = new Date(now.getTime() + itemSplit[1] * oneDay);
                            endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 23:59:59";
                        } else if (id.indexOf("-") > -1) {
                            date = new Date(now.getTime() - itemSplit[1] * oneDay);
                            startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                        }
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));

                        break;
                    case "Week":
                        n = (now.getDay() == 0 ? 7 : now.getDay()) - 1;
                        if (id.indexOf("+") > -1) {
                            date = new Date(now.getTime() - n * oneDay);
                            endDate = new Date(now.getTime() + (6 - n) * oneDay + parseInt(itemSplit[1]) * 7 * oneDay);
                            startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                            endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                        } else if (id.indexOf("-") > -1) {
                            date = new Date(now.getTime() - (n + parseInt(itemSplit[1]) * 7) * oneDay);
                            endDate = new Date(now.getTime() + (6 - n) * oneDay);
                            startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                            endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                        }
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Month":
                        startTime = now.getFullYear() + "-" + (now.getMonth() + 1 - parseInt(itemSplit[1])) + "-1 00:00:00";
                        var currentMonth = now.getMonth();
                        endDate = new Date(new Date(now.getFullYear(), ++currentMonth, 1) - oneDay); //本月最后一天
                        endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    case "Year":
                        startTime = (now.getFullYear() - parseInt(itemSplit[1])) + "-1-1 00:00:00"; //itemSplit[1]年前年份的第一天
                        var currentYear = now.getFullYear();
                        endDate = new Date(new Date(++currentYear, 0, 1) - oneDay); //本年最后一天
                        endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " 23:59:59";
                        $('#txt-datetimestart').val(pageEvent.dateFullformat(startTime, "yyyy-MM-dd"));
                        $('#txt-datetimeend').val(pageEvent.dateFullformat(endTime, "yyyy-MM-dd"));
                        break;
                    default:
                        break;
                }
            }
        }
    };

    page.init();
})();
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}
